﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RESTAURANT.Class;
using Excel = Microsoft.Office.Interop.Excel;
using System.Threading;
using DevComponents.DotNetBar;

namespace RESTAURANT
{
    public partial class frmMainForm : Form
    {
        #region KHAI BAO TOAN CUC

        public string Admin = "";
        private DataTable dt_data = null;
        private DataTable dt_data_log = null;
        private DataTable dt_nhan_vien = null;
        private DataTable dt_datatable = null;
        private BindingManagerBase dhh_datatable = null;
        private bool bThem_moi = false;
        private int i_select = 1;
        private const string Noi_dung = "Nhập nội dung cần tìm";
        public int mMachineNumber = 1;
        public int gMachineNumber = 1;
        public string Mat_khau = "";
        public string setID;

        public frmMainForm()
        {
            InitializeComponent();
        }

        private void frmMainForm_Load(object sender, EventArgs e)
        {
            BP_HideAll();
            riQL_BoPhan.Checked = true;
            UsingSql.LoadTableSet();
        }

        private void frmMainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.OpenForms["frmSignInNoCard"].Visible = true;                      
        }

        #endregion

        #region QUAN LY BO PHAN

        private void BP_HideAll()
        {
            groupBoPhan.Visible = false;
            gvBoPhan.Visible = false;
            txtBP_Tim.Visible = false;
        }

        private void BP_EnableTrueAll()
        {
            txtBP_GhiChu.Enabled = true;
            txtBP_MaBP.Enabled = true;
            txtBP_TenBP.Enabled = true;
        }

        private void BP_EnableFalseAll()
        {
            txtBP_GhiChu.Enabled = false;
            txtBP_MaBP.Enabled = false;
            txtBP_TenBP.Enabled = false;
        }

        private void BP_ResetAll()
        {
            txtBP_GhiChu.Text = "";
            txtBP_MaBP.Text = UsingSql.GetDepartmentIDMax().ToString();
            txtBP_TenBP.Text = "";
            bThem_moi = false;
        }

        private void riQL_BoPhan_Click(object sender, EventArgs e)
        {
            try
            {
                BP_HideAll();
            }
            catch (Exception)
            {
            }
        }

        private void BP_Load_Department()
        {
            string sql = @"select * from department where deleted='false' order by departmentname";
            dt_datatable = UsingSql.GetQuery(sql);
            dhh_datatable = BindingContext[dt_datatable];
            dhh_datatable.PositionChanged += new EventHandler(dhh_datatable_PositionChanged_Department);
            gvBoPhan.AutoGenerateColumns = false;
            gvBoPhan.DataSource = dt_datatable;
            BP_Xuat_thong_tin();
        }

        private void BP_Xuat_thong_tin()
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_datatable.Current;
                txtBP_MaBP.Text = drv["departmentcode"].ToString();
                txtBP_TenBP.Text = drv["departmentname"].ToString();
                txtBP_GhiChu.Text = drv["note"].ToString();
            }
            catch (Exception)
            {
            }
        }

        private void BP_Nhap_thong_tin(Department d)
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_datatable.Current;
                if (bThem_moi) drv["departmentid"] = d.DepartmentID;
                drv["departmentcode"] = d.DepartmentCode;
                drv["departmentname"] = d.DepartmentName;
                drv["note"] = d.Note;
            }
            catch (Exception)
            {
            }
        }

        private bool BP_Kiem_tra_thong_tin()
        {
            if (txtBP_MaBP.Text == "")
            {
                MessageBox.Show("Mã bộ phận không được rỗng.");
                return false;
            }
            if (txtBP_TenBP.Text == "")
            {
                MessageBox.Show("Tên bộ phận không được rỗng.");
                return false;
            }
            return true;
        }

        private Department BP_Get_thong_tin()
        {
            Department d = new Department();
            d.DepartmentID = UsingSql.GetDepartmentIDMax();
            d.DepartmentCode = txtBP_MaBP.Text;
            d.DepartmentName = txtBP_TenBP.Text;
            d.Note = txtBP_GhiChu.Text;
            d.Deleted = false;
            return d;
        }

        private void dhh_datatable_PositionChanged_Department(object sender, EventArgs e)
        {
            try
            {
                if (bThem_moi == false) BP_Xuat_thong_tin();
            }
            catch (Exception)
            {
            }
        }

        private void btnBP_TaoMoi_Click(object sender, EventArgs e)
        {
            try
            {
                i_select = 1;
                BP_HideAll();
                groupBoPhan.Location = new Point(10, 151);
                groupBoPhan.Size = new Size(437, 249);
                groupBoPhan.Visible = true;
                gvBoPhan.Location = new Point(453, 151);
                gvBoPhan.Size = new Size(563, 249);
                gvBoPhan.Visible = true;
                BP_Load_Department();
                BP_EnableTrueAll();
                BP_ResetAll();
                btnBP_GhiNhan.Text = "Ghi Nhận";
                btnBP_Huy.Text = "Hủy";
                bThem_moi = true;
                gvBoPhan.Enabled = false;
            }
            catch (Exception)
            {
            }
        }

        private void btnBP_DieuChinh_Click(object sender, EventArgs e)
        {
            try
            {
                i_select = 2;
                BP_HideAll();
                groupBoPhan.Location = new Point(10, 151);
                groupBoPhan.Size = new Size(437, 249);
                groupBoPhan.Visible = true;
                gvBoPhan.Location = new Point(453, 151);
                gvBoPhan.Size = new Size(563, 249);
                gvBoPhan.Visible = true;
                txtBP_Tim.Location = new Point(9, 125);
                txtBP_Tim.Visible = true;
                BP_EnableFalseAll();
                gvBoPhan.Enabled = true;
                txtBP_Tim.Text = Noi_dung;
                btnBP_GhiNhan.Text = "Chỉnh Sửa";
                btnBP_Huy.Text = "Xóa";
                BP_Load_Department();
            }
            catch (Exception)
            {
            }
        }

        private void btnBP_GhiNhan_Click(object sender, EventArgs e)
        {
            try
            {
                if (i_select == 1)//Tao moi
                {
                    if (btnBP_GhiNhan.Text == "Tạo Mới")
                    {
                        BP_EnableTrueAll();
                        BP_ResetAll();
                        btnBP_GhiNhan.Text = "Ghi Nhận";
                        btnBP_Huy.Text = "Hủy";
                        bThem_moi = true;
                        gvBoPhan.Enabled = false;
                    }
                    else
                    {
                        if (BP_Kiem_tra_thong_tin())
                        {
                            Department d = BP_Get_thong_tin();
                            if (UsingSql.insert_Department(d) == 1)
                            {
                                dhh_datatable.AddNew();
                                BP_Nhap_thong_tin(d);
                                dhh_datatable.EndCurrentEdit();
                                BP_EnableFalseAll();
                                btnBP_GhiNhan.Text = "Tạo Mới";
                                btnBP_Huy.Text = "Hủy";
                                bThem_moi = false;
                                gvBoPhan.Enabled = true;
                            }
                            else
                            {
                                MessageBox.Show("Mã bộ phận đã tồn tại!");
                            }
                        }
                    }
                }
                else//Dieu chinh
                {
                    if (btnBP_GhiNhan.Text == "Chỉnh Sửa")
                    {
                        BP_EnableTrueAll();
                        btnBP_GhiNhan.Text = "Ghi Nhận";
                        btnBP_Huy.Text = "Hủy";
                        bThem_moi = false;
                        gvBoPhan.Enabled = false;
                    }
                    else
                    {
                        if (BP_Kiem_tra_thong_tin())
                        {
                            Department d = BP_Get_thong_tin();
                            DataRowView drv = (DataRowView)dhh_datatable.Current;
                            d.DepartmentID = Convert.ToInt32(drv["departmentid"]);
                            if (UsingSql.update_Department(d) == 1)
                            {
                                BP_Nhap_thong_tin(d);
                                dhh_datatable.EndCurrentEdit();
                                BP_EnableFalseAll();
                                btnBP_GhiNhan.Text = "Chỉnh Sửa";
                                btnBP_Huy.Text = "Xóa";
                                bThem_moi = false;
                                gvBoPhan.Enabled = true;
                            }
                            else
                            {
                                MessageBox.Show("Mã bộ phận đã tồn tại!!");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void btnBP_Huy_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnBP_Huy.Text == "Hủy")
                {
                    btnBP_GhiNhan.Text = "Chỉnh Sửa";
                    btnBP_Huy.Text = "Xóa";
                    if (i_select == 1)
                    {
                        btnBP_GhiNhan.Text = "Tạo Mới";
                        btnBP_Huy.Text = "Hủy";
                    }
                    BP_EnableFalseAll();
                    gvBoPhan.Enabled = true;
                    bThem_moi = false;
                    BP_Xuat_thong_tin();
                }
                else
                {
                    if (MessageBox.Show("Bạn có muốn xóa thông tin này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        DataRowView drv = (DataRowView)dhh_datatable.Current;
                        string departmentID = drv["departmentID"].ToString();
                        if (UsingSql.delete_Department(departmentID) == 1)
                        {
                            dhh_datatable.RemoveAt(dhh_datatable.Position);
                            dhh_datatable.EndCurrentEdit();
                            BP_Xuat_thong_tin();
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void txtBP_Tim_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string tim = txtBP_Tim.Text.Trim();
                string chuoi_tim = "departmentcode='" + tim + "'";
                dt_datatable.DefaultView.RowFilter = chuoi_tim;
                if (dt_datatable.DefaultView.Count == 0)
                {
                    chuoi_tim = "departmentname like '*" + tim + "*'";
                    dt_datatable.DefaultView.RowFilter = chuoi_tim;
                }
                BP_Xuat_thong_tin();
            }
            catch (Exception)
            {
            }
        }

        private void txtBP_Tim_Click(object sender, EventArgs e)
        {
            txtBP_Tim.SelectAll();
        }

        private void btnBP_Exit_Click(object sender, EventArgs e)
        {
            BP_HideAll();
        }

        #endregion

        #region QUAN LY CHUC VU

        private void CV_HideAll()
        {
            groupChucVu.Visible = false;
            gvChucVu.Visible = false;
            txtCV_Tim.Visible = false;
        }

        private void CV_EnableTrueAll()
        {
            txtCV_GhiChu.Enabled = true;
            txtCV_MaCV.Enabled = true;
            txtCV_TenCV.Enabled = true;
        }

        private void CV_EnableFalseAll()
        {
            txtCV_GhiChu.Enabled = false;
            txtCV_MaCV.Enabled = false;
            txtCV_TenCV.Enabled = false;
        }

        private void CV_ResetAll()
        {
            txtCV_GhiChu.Text = "";
            txtCV_MaCV.Text = UsingSql.GetPositionIDMax().ToString();
            txtCV_TenCV.Text = "";
            bThem_moi = false;
        }

        private void riQL_ChucVu_Click(object sender, EventArgs e)
        {
            try
            {
                CV_HideAll();
            }
            catch (Exception)
            {
            }
        }

        private void CV_Load_Position()
        {
            string sql = @"select * from position where deleted='false'";
            dt_datatable = UsingSql.GetQuery(sql);
            dhh_datatable = BindingContext[dt_datatable];
            dhh_datatable.PositionChanged += new EventHandler(dhh_datatable_PositionChanged_Position);
            gvChucVu.AutoGenerateColumns = false;
            gvChucVu.DataSource = dt_datatable;
            CV_Xuat_thong_tin();
        }

        private void CV_Xuat_thong_tin()
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_datatable.Current;
                txtCV_MaCV.Text = drv["positioncode"].ToString();
                txtCV_TenCV.Text = drv["positionname"].ToString();
                txtCV_GhiChu.Text = drv["note"].ToString();
            }
            catch (Exception)
            {
            }
        }

        private void CV_Nhap_thong_tin(Position p)
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_datatable.Current;
                if (bThem_moi) drv["positionid"] = p.PositionID;
                drv["positioncode"] = p.PositionCode;
                drv["positionname"] = p.PositionName;
                drv["note"] = p.Note;
            }
            catch (Exception)
            {
            }
        }

        private bool CV_Kiem_tra_thong_tin()
        {
            if (txtCV_MaCV.Text == "")
            {
                MessageBox.Show("Mã Chức vụ không được rỗng.");
                return false;
            }
            if (txtCV_TenCV.Text == "")
            {
                MessageBox.Show("Tên chức vụ không được rỗng.");
                return false;
            }
            return true;
        }

        private Position CV_Get_thong_tin()
        {
            Position p = new Position();
            p.PositionID = UsingSql.GetPositionIDMax();
            p.PositionCode = txtCV_MaCV.Text;
            p.PositionName = txtCV_TenCV.Text;
            p.Note = txtCV_GhiChu.Text;
            p.Deleted = false;
            return p;
        }

        private void dhh_datatable_PositionChanged_Position(object sender, EventArgs e)
        {
            try
            {
                if (bThem_moi == false) CV_Xuat_thong_tin();
            }
            catch (Exception)
            {
            }
        }

        private void btnCV_TaoMoi_Click(object sender, EventArgs e)
        {
            try
            {
                i_select = 1;
                CV_HideAll();
                groupChucVu.Location = new Point(10, 151);
                groupChucVu.Size = new Size(437, 249);
                groupChucVu.Visible = true;
                gvChucVu.Location = new Point(453, 151);
                gvChucVu.Size = new Size(563, 249);
                gvChucVu.Visible = true;
                CV_Load_Position();
                CV_EnableTrueAll();
                CV_ResetAll();
                btnCV_GhiNhan.Text = "Ghi Nhận";
                btnCV_Huy.Text = "Hủy";
                bThem_moi = true;
                gvChucVu.Enabled = false;
            }
            catch (Exception)
            {
            }
        }

        private void btnCV_DieuChinh_Click(object sender, EventArgs e)
        {
            try
            {
                i_select = 2;
                CV_HideAll();
                groupChucVu.Location = new Point(10, 151);
                groupChucVu.Size = new Size(437, 249);
                groupChucVu.Visible = true;
                gvChucVu.Location = new Point(453, 151);
                gvChucVu.Size = new Size(563, 249);
                gvChucVu.Visible = true;
                txtCV_Tim.Location = new Point(9, 125);
                txtCV_Tim.Visible = true;
                CV_EnableFalseAll();
                gvChucVu.Enabled = true;
                txtCV_Tim.Text = Noi_dung;
                btnCV_GhiNhan.Text = "Chỉnh Sửa";
                btnCV_Huy.Text = "Xóa";
                CV_Load_Position();
            }
            catch (Exception)
            {
            }
        }

        private void btnCV_GhiNhan_Click(object sender, EventArgs e)
        {
            try
            {
                if (i_select == 1)//Tao moi
                {
                    if (btnCV_GhiNhan.Text == "Tạo Mới")
                    {
                        CV_EnableTrueAll();
                        CV_ResetAll();
                        btnCV_GhiNhan.Text = "Ghi Nhận";
                        btnCV_Huy.Text = "Hủy";
                        bThem_moi = true;
                        gvChucVu.Enabled = false;
                    }
                    else
                    {
                        if (CV_Kiem_tra_thong_tin())
                        {
                            Position p = CV_Get_thong_tin();
                            if (UsingSql.insert_position(p) == 1)
                            {
                                dhh_datatable.AddNew();
                                CV_Nhap_thong_tin(p);
                                dhh_datatable.EndCurrentEdit();
                                CV_EnableFalseAll();
                                btnCV_GhiNhan.Text = "Tạo Mới";
                                btnCV_Huy.Text = "Hủy";
                                bThem_moi = false;
                                gvChucVu.Enabled = true;
                            }
                            else
                            {
                                MessageBox.Show("Mã chức vụ đã tồn tại!");
                            }
                        }
                    }
                }
                else//Dieu chinh
                {
                    if (btnCV_GhiNhan.Text == "Chỉnh Sửa")
                    {
                        CV_EnableTrueAll();
                        btnCV_GhiNhan.Text = "Ghi Nhận";
                        btnCV_Huy.Text = "Hủy";
                        bThem_moi = false;
                        gvChucVu.Enabled = false;
                    }
                    else
                    {
                        if (CV_Kiem_tra_thong_tin())
                        {
                            Position p = CV_Get_thong_tin();
                            DataRowView drv = (DataRowView)dhh_datatable.Current;
                            p.PositionID = Convert.ToInt32(drv["positionid"]);
                            if (UsingSql.update_position(p) == 1)
                            {
                                CV_Nhap_thong_tin(p);
                                dhh_datatable.EndCurrentEdit();
                                CV_EnableFalseAll();
                                btnCV_GhiNhan.Text = "Chỉnh Sửa";
                                btnCV_Huy.Text = "Xóa";
                                bThem_moi = false;
                                gvChucVu.Enabled = true;
                            }
                            else
                            {
                                MessageBox.Show("Mã chức vụ đã tồn tại!!");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void btnCV_Huy_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnCV_Huy.Text == "Hủy")
                {
                    btnCV_GhiNhan.Text = "Chỉnh Sửa";
                    btnCV_Huy.Text = "Xóa";
                    if (i_select == 1)
                    {
                        btnCV_GhiNhan.Text = "Tạo Mới";
                        btnCV_Huy.Text = "Hủy";
                    }
                    CV_EnableFalseAll();
                    gvChucVu.Enabled = true;
                    bThem_moi = false;
                    CV_Xuat_thong_tin();
                }
                else
                {
                    if (MessageBox.Show("Bạn có muốn xóa thông tin này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        DataRowView drv = (DataRowView)dhh_datatable.Current;
                        string positionID = drv["positionID"].ToString();
                        if (UsingSql.delete_position(positionID) == 1)
                        {
                            dhh_datatable.RemoveAt(dhh_datatable.Position);
                            dhh_datatable.EndCurrentEdit();
                            CV_Xuat_thong_tin();
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void txtCV_Tim_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string tim = txtCV_Tim.Text.Trim();
                string chuoi_tim = "positioncode='" + tim + "'";
                dt_datatable.DefaultView.RowFilter = chuoi_tim;
                if (dt_datatable.DefaultView.Count == 0)
                {
                    chuoi_tim = "positionname like '*" + tim + "*'";
                    dt_datatable.DefaultView.RowFilter = chuoi_tim;
                }
                CV_Xuat_thong_tin();
            }
            catch (Exception)
            {
            }
        }

        private void txtCV_Tim_Click(object sender, EventArgs e)
        {
            txtCV_Tim.SelectAll();
        }

        private void btnCV_Exit_Click(object sender, EventArgs e)
        {
            CV_HideAll();
        }

        #endregion

        #region QUAN LY CA LAM VIEC

        private void CALV_HideAll()
        {
            groupCALV.Visible = false;
            gvCaLamViec.Visible = false;
            txtCALV_Tim.Visible = false;
        }

        private void CALV_EnableTrueAll()
        {
            txtCALV_GhiChu.Enabled = true;

            txtCALV_TenCALV.Enabled = true;
            dtiCALV_GioBD.Enabled = true;
            dtiCALV_GioKT.Enabled = true;
        }

        private void CALV_EnableFalseAll()
        {
            txtCALV_GhiChu.Enabled = false;

            txtCALV_TenCALV.Enabled = false;
            dtiCALV_GioBD.Enabled = false;
            dtiCALV_GioKT.Enabled = false;
        }

        private void CALV_ResetAll()
        {
            txtCALV_GhiChu.Text = "";

            txtCALV_TenCALV.Text = "";
            dtiCALV_GioBD.Value = DateTime.Parse("00:00");
            dtiCALV_GioKT.Value = DateTime.Parse("00:00");
            bThem_moi = false;
        }

        private void riQL_CALV_Click(object sender, EventArgs e)
        {
            try
            {
                CALV_HideAll();
            }
            catch (Exception)
            {
            }
        }

        private void CALV_Load_Shift()
        {
            string sql = @"select * from shift where deleted='false'";
            dt_datatable = UsingSql.GetQuery(sql);
            dhh_datatable = BindingContext[dt_datatable];
            dhh_datatable.PositionChanged += new EventHandler(dhh_datatable_PositionChanged_Shift);
            gvCaLamViec.AutoGenerateColumns = false;
            gvCaLamViec.DataSource = dt_datatable;
            CALV_Xuat_thong_tin();
        }

        private void CALV_Xuat_thong_tin()
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_datatable.Current;
                txtCALV_MaCALV.Text = drv["shiftid"].ToString();
                txtCALV_TenCALV.Text = drv["shiftname"].ToString();
                dtiCALV_GioBD.Value = DateTime.Parse(drv["shiftbegin"].ToString());
                dtiCALV_GioKT.Value = DateTime.Parse(drv["shiftend"].ToString());
                txtCALV_GhiChu.Text = drv["note"].ToString();
            }
            catch (Exception)
            {
            }
        }

        private void CALV_Nhap_thong_tin(Shift s)
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_datatable.Current;
                if (bThem_moi) drv["shiftid"] = s.ShiftID;
                drv["shiftname"] = s.ShiftName;
                drv["shiftbegin"] = s.ShiftBegin;
                drv["shiftend"] = s.ShiftEnd;
                drv["note"] = s.Note;
            }
            catch (Exception)
            {
            }
        }

        private bool CALV_Kiem_tra_thong_tin()
        {
            if (txtCALV_TenCALV.Text == "")
            {
                MessageBox.Show("Tên ca làm việc không được rỗng.");
                return false;
            }
            if (dtiCALV_GioBD.Value == null)
            {
                MessageBox.Show("Giờ bắt đầu ca làm việc không được rỗng.");
                return false;
            }
            if (dtiCALV_GioKT.Value == null)
            {
                MessageBox.Show("Giờ kết thúc ca làm việc không được rỗng.");
                return false;
            }
            return true;
        }

        private Shift CALV_Get_thong_tin()
        {
            Shift s = new Shift();
            s.ShiftID = UsingSql.GetShiftIDMax();
            s.ShiftName = txtCALV_TenCALV.Text;
            s.ShiftBegin = dtiCALV_GioBD.Value;
            s.ShiftEnd = dtiCALV_GioKT.Value;
            s.Note = txtCALV_GhiChu.Text;
            s.Deleted = false;
            return s;
        }

        private void dhh_datatable_PositionChanged_Shift(object sender, EventArgs e)
        {
            try
            {
                if (bThem_moi == false) CALV_Xuat_thong_tin();
            }
            catch (Exception)
            {
            }
        }

        private void btnCALV_TaoMoi_Click(object sender, EventArgs e)
        {
            try
            {
                i_select = 1;
                CALV_HideAll();
                groupCALV.Location = new Point(10, 151);
                groupCALV.Size = new Size(437, 321);
                groupCALV.Visible = true;
                gvCaLamViec.Location = new Point(453, 151);
                gvCaLamViec.Size = new Size(563, 321);
                gvCaLamViec.Visible = true;
                CALV_Load_Shift();
                CALV_EnableTrueAll();
                CALV_ResetAll();
                btnCALV_GhiNhan.Text = "Ghi Nhận";
                btnCALV_Huy.Text = "Hủy";
                bThem_moi = true;
                gvCaLamViec.Enabled = false;
            }
            catch (Exception)
            {
            }
        }

        private void btnCALV_DieuChinh_Click(object sender, EventArgs e)
        {
            try
            {
                i_select = 2;
                CALV_HideAll();
                groupCALV.Location = new Point(10, 151);
                groupCALV.Size = new Size(437, 321);
                groupCALV.Visible = true;
                gvCaLamViec.Location = new Point(453, 151);
                gvCaLamViec.Size = new Size(563, 321);
                gvCaLamViec.Visible = true;
                txtCALV_Tim.Location = new Point(9, 125);
                txtCALV_Tim.Visible = true;
                CALV_EnableFalseAll();
                gvCaLamViec.Enabled = true;
                txtCALV_Tim.Text = Noi_dung;
                btnCALV_GhiNhan.Text = "Chỉnh Sửa";
                btnCALV_Huy.Text = "Xóa";
                CALV_Load_Shift();
            }
            catch (Exception)
            {
            }
        }

        private void btnCALV_GhiNhan_Click(object sender, EventArgs e)
        {
            try
            {
                if (i_select == 1)//Tao moi
                {
                    if (btnCALV_GhiNhan.Text == "Tạo Mới")
                    {
                        CALV_EnableTrueAll();
                        CALV_ResetAll();
                        btnCALV_GhiNhan.Text = "Ghi Nhận";
                        btnCALV_Huy.Text = "Hủy";
                        bThem_moi = true;
                        gvCaLamViec.Enabled = false;
                    }
                    else
                    {
                        if (CALV_Kiem_tra_thong_tin())
                        {
                            Shift s = CALV_Get_thong_tin();
                            if (UsingSql.insert_shift(s) == 1)
                            {
                                dhh_datatable.AddNew();
                                CALV_Nhap_thong_tin(s);
                                dhh_datatable.EndCurrentEdit();
                                CALV_EnableFalseAll();
                                btnCALV_GhiNhan.Text = "Tạo Mới";
                                btnCALV_Huy.Text = "Hủy";
                                bThem_moi = false;
                                gvCaLamViec.Enabled = true;
                            }
                            else
                            {
                                MessageBox.Show("Tên ca làm việc đã tồn tại!");
                            }
                        }
                    }
                }
                else//Dieu chinh
                {
                    if (btnCALV_GhiNhan.Text == "Chỉnh Sửa")
                    {
                        CALV_EnableTrueAll();
                        btnCALV_GhiNhan.Text = "Ghi Nhận";
                        btnCALV_Huy.Text = "Hủy";
                        bThem_moi = false;
                        gvCaLamViec.Enabled = false;
                    }
                    else
                    {
                        if (CALV_Kiem_tra_thong_tin())
                        {
                            Shift s = CALV_Get_thong_tin();
                            DataRowView drv = (DataRowView)dhh_datatable.Current;
                            s.ShiftID = Convert.ToInt32(drv["shiftid"]);
                            if (UsingSql.update_shift(s) == 1)
                            {
                                CALV_Nhap_thong_tin(s);
                                dhh_datatable.EndCurrentEdit();
                                CALV_EnableFalseAll();
                                btnCALV_GhiNhan.Text = "Chỉnh Sửa";
                                btnCALV_Huy.Text = "Xóa";
                                bThem_moi = false;
                                gvCaLamViec.Enabled = true;
                            }
                            else
                            {
                                MessageBox.Show("Tên ca làm việc đã tồn tại!!");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void btnCALV_Huy_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnCALV_Huy.Text == "Hủy")
                {
                    btnCALV_GhiNhan.Text = "Chỉnh Sửa";
                    btnCALV_Huy.Text = "Xóa";
                    if (i_select == 1)
                    {
                        btnCALV_GhiNhan.Text = "Tạo Mới";
                        btnCALV_Huy.Text = "Hủy";
                    }
                    CALV_EnableFalseAll();
                    gvCaLamViec.Enabled = true;
                    bThem_moi = false;
                    CALV_Xuat_thong_tin();
                }
                else
                {
                    if (MessageBox.Show("Bạn có muốn xóa thông tin này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        DataRowView drv = (DataRowView)dhh_datatable.Current;
                        string shiftID = drv["shiftid"].ToString();
                        if (UsingSql.delete_shift(shiftID) == 1)
                        {
                            dhh_datatable.RemoveAt(dhh_datatable.Position);
                            dhh_datatable.EndCurrentEdit();
                            CALV_Xuat_thong_tin();
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void txtCALV_Tim_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string tim = txtCALV_Tim.Text.Trim();
                string chuoi_tim = "shiftname='" + tim + "'";
                dt_datatable.DefaultView.RowFilter = chuoi_tim;
                if (dt_datatable.DefaultView.Count == 0)
                {
                    chuoi_tim = "shiftname like '*" + tim + "*'";
                    dt_datatable.DefaultView.RowFilter = chuoi_tim;
                }
                CALV_Xuat_thong_tin();
            }
            catch (Exception)
            {
            }
        }

        private void txtCALV_Tim_Click(object sender, EventArgs e)
        {
            txtCALV_Tim.SelectAll();
        }

        private void btnCALV_Exit_Click(object sender, EventArgs e)
        {
            CALV_HideAll();
        }

        #endregion

        #region QUAN LY NHAN VIEN

        private void NV_HideAll()
        {
            groupNhanVien.Visible = false;
            groupNV_taikhoan.Visible = false;
            groupNV_ghichu.Visible = false;
            gvNhanVien.Visible = false;
            txtNV_Tim.Visible = false;
        }

        private void NV_EnableTrueAll()
        {
            txtNV_MaNV.Enabled = true;
            txtNV_TenNV.Enabled = true;
            dtiNV_NgaySinh.Enabled = true;
            ckbNV_GioiTinh_Nam.Enabled = true;
            ckbNV_GioiTinh_Nu.Enabled = true;
            txtNV_DienThoai.Enabled = true;
            txtNV_DiaChi.Enabled = true;
            cbbNV_BoPhan.Enabled = true;
            cbbNV_ChucVu.Enabled = true;
            cbbNV_QuyenHan.Enabled = true;
            cbbNV_CaLV1.Enabled = true;
            cbbNV_CaLV2.Enabled = true;
            txtNV_GhiChu.Enabled = true;
            txtNV_MatKhau.Enabled = true;
            txtNV_TaiKhoan.Enabled = true;
        }

        private void NV_EnableFalseAll()
        {
            txtNV_MaNV.Enabled = false;
            txtNV_TenNV.Enabled = false;
            dtiNV_NgaySinh.Enabled = false;
            ckbNV_GioiTinh_Nam.Enabled = false;
            ckbNV_GioiTinh_Nu.Enabled = false;
            txtNV_DienThoai.Enabled = false;
            txtNV_DiaChi.Enabled = false;
            cbbNV_BoPhan.Enabled = false;
            cbbNV_ChucVu.Enabled = false;
            cbbNV_QuyenHan.Enabled = false;
            txtNV_TaiKhoan.Enabled = false;
            txtNV_MatKhau.Enabled = false;
            cbbNV_CaLV1.Enabled = false;
            cbbNV_CaLV2.Enabled = false;
            txtNV_GhiChu.Enabled = false;
        }

        private void NV_ResetAll()
        {
            txtNV_MaNV.ResetText();
            txtNV_TenNV.ResetText();
            dtiNV_NgaySinh.Value = DateTime.Now;
            ckbNV_GioiTinh_Nam.Checked = true;
            ckbNV_GioiTinh_Nu.Checked = false;
            txtNV_DienThoai.ResetText();
            txtNV_DiaChi.ResetText();
            cbbNV_BoPhan.Text = "Chưa xác định";
            cbbNV_ChucVu.Text = "Chưa xác định";
            cbbNV_QuyenHan.Text = "Chưa xác định";
            txtNV_TaiKhoan.ResetText();
            txtNV_MatKhau.ResetText();
            cbbNV_CaLV1.Text = "Không chọn";
            cbbNV_CaLV2.Text = "Không chọn";
            txtNV_GhiChu.ResetText();
            bThem_moi = false;
        }

        private void riQL_NV_Click(object sender, EventArgs e)
        {
            try
            {
                NV_HideAll();
                NV_Com_HideAll();
            }
            catch (Exception)
            {
            }
        }

        private void NV_Load_Employee()
        {
            dt_datatable = UsingSql.getAllEmpInfo();
            dhh_datatable = BindingContext[dt_datatable];
            dhh_datatable.PositionChanged += new EventHandler(dhh_datatable_PositionChanged_Employee);
            gvNhanVien.AutoGenerateColumns = false;
            gvNhanVien.DataSource = dt_datatable;
            NV_Xuat_thong_tin();
        }

        private void NV_Xuat_thong_tin()
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_datatable.Current;
                txtNV_MaNV.Text = drv["employeecode"].ToString();
                txtNV_TenNV.Text = drv["employeefirstname"].ToString().Trim()
                    + " "
                    + drv["employeelastname"].ToString().Trim();
                if (drv["employeebirthday"].ToString().Trim() != "")
                {
                    dtiNV_NgaySinh.Value = DateTime.Parse(drv["employeebirthday"].ToString());
                }
                else
                {
                    dtiNV_NgaySinh.Text = "";
                }
                if (drv["employeesex"].ToString() == "True")
                {
                    ckbNV_GioiTinh_Nam.Checked = true;
                    ckbNV_GioiTinh_Nu.Checked = false;
                }
                else
                {
                    ckbNV_GioiTinh_Nam.Checked = false;
                    ckbNV_GioiTinh_Nu.Checked = true;
                }
                txtNV_DienThoai.Text = drv["employeephone"].ToString();
                txtNV_DiaChi.Text = drv["employeeaddress"].ToString();
                cbbNV_BoPhan.SelectedValue = drv["departmentid"].ToString();
                cbbNV_ChucVu.SelectedValue = drv["positionid"].ToString();
                cbbNV_QuyenHan.SelectedValue = drv["roleid"].ToString();
                txtNV_TaiKhoan.Text = drv["employeeusername"].ToString();
                txtNV_MatKhau.Text = drv["employeepassword"].ToString();
                cbbNV_CaLV1.SelectedValue = drv["shiftid_1"].ToString();
                cbbNV_CaLV2.SelectedValue = drv["shiftid_2"].ToString();
                txtNV_GhiChu.Text = drv["note"].ToString(); ;
            }
            catch (Exception)
            {
            }
        }

        private void NV_Nhap_thong_tin(Employee e)
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_datatable.Current;
                if (bThem_moi) drv["employeeid"] = e.EmpID;
                drv["employeecode"] = e.EmpCode;
                drv["employeefirstname"] = e.EmpFirstName;
                drv["employeelastname"] = e.EmpLastName;
                drv["employeebirthday"] = e.EmpBirthday;
                drv["employeesex"] = e.EmpSex;
                drv["employeephone"] = e.EmpPhone;
                drv["employeeaddress"] = e.EmpAddress;
                drv["departmentid"] = e.DepartmentID;
                drv["departmentname"] = e.DepartmentName;
                drv["positionid"] = e.PositionID;
                drv["positionname"] = e.PositionName;
                drv["roleid"] = e.RoleID;
                drv["rolename"] = e.RoleName;
                drv["shiftid_1"] = e.ShiftID1;
                drv["shiftid_2"] = e.ShiftID2;
                drv["note"] = e.Note;
            }
            catch (Exception)
            {
            }
        }

        private bool NV_Kiem_tra_thong_tin()
        {
            if (txtNV_MaNV.Text == string.Empty)
            {
                MessageBox.Show("Mã nhân viên không được rỗng");
                return false;
            }
            if (txtNV_TenNV.Text == "")
            {
                MessageBox.Show("Tên nhân viên không được rỗng.");
                return false;
            }
            return true;
        }

        private Employee NV_Get_thong_tin()
        {
            Employee e = new Employee();
            e.EmpID = UsingSql.getEmpIDMax().ToString();
            e.EmpCode = Convert.ToInt32(txtNV_MaNV.Text);
            string tenNV = txtNV_TenNV.Text.Trim();
            string[] mtenNV = UsingSql.SplitEmpName(tenNV);
            e.EmpFirstName = mtenNV[0];
            e.EmpLastName = mtenNV[1];
            e.EmpBirthday = dtiNV_NgaySinh.Value;
            e.EmpAddress = txtNV_DiaChi.Text;
            e.EmpPhone = txtNV_DienThoai.Text;
            if (ckbNV_GioiTinh_Nam.Checked == true)
            {
                e.EmpSex = true;
            }
            else if (ckbNV_GioiTinh_Nu.Checked == true)
            {
                e.EmpSex = false;
            }

            e.DepartmentID = Convert.ToInt32(cbbNV_BoPhan.SelectedValue.ToString());
            e.DepartmentName = cbbNV_BoPhan.Text;
            e.PositionID = Convert.ToInt32(cbbNV_ChucVu.SelectedValue.ToString());
            e.PositionName = cbbNV_ChucVu.Text;
            e.RoleID = cbbNV_QuyenHan.SelectedValue.ToString();
            e.RoleName = cbbNV_QuyenHan.Text;
            e.ShiftID1 = Convert.ToInt32(cbbNV_CaLV1.SelectedValue.ToString());
            e.ShiftID2 = Convert.ToInt32(cbbNV_CaLV2.SelectedValue.ToString());


            e.EmpUser = txtNV_TaiKhoan.Text;
            if (i_select == 2 && Mat_khau == txtNV_MatKhau.Text)
                e.EmpPass = txtNV_MatKhau.Text;
            else
                e.EmpPass = UsingSql.Encrypt(txtNV_MatKhau.Text);
            e.Note = txtNV_GhiChu.Text;
            e.Deleted = false;
            return e;
        }

        private void NV_getDepartmentList()
        {
            DataTable DeptList = UsingSql.getDepartmentList();
            DataRow row = DeptList.NewRow();
            row[0] = 0;
            row[1] = "Chưa xác định";
            DeptList.Rows.Add(row);
            cbbNV_BoPhan.DataSource = DeptList;
            cbbNV_BoPhan.ValueMember = DeptList.Columns["DepartmentCode"].ToString();
            cbbNV_BoPhan.DisplayMember = DeptList.Columns["DepartmentName"].ToString();
        }

        private void NV_getPositionList()
        {
            DataTable PosList = UsingSql.getPositionList();
            DataRow row = PosList.NewRow();
            row[0] = 0;
            row[1] = "Chưa xác định";
            PosList.Rows.Add(row);
            cbbNV_ChucVu.DataSource = PosList;
            cbbNV_ChucVu.ValueMember = PosList.Columns["PositionCode"].ToString();
            cbbNV_ChucVu.DisplayMember = PosList.Columns["PositionName"].ToString();
        }

        private void NV_getShiftList()
        {
            DataTable ShiftList1 = UsingSql.getShiftList();
            DataRow row1 = ShiftList1.NewRow();
            row1["ShiftID"] = 0;
            row1["ShiftName"] = "Không chọn";
            ShiftList1.Rows.Add(row1);
            cbbNV_CaLV1.DataSource = ShiftList1;
            cbbNV_CaLV1.ValueMember = "ShiftID";
            cbbNV_CaLV1.DisplayMember = "ShiftName";

            DataTable ShiftList2 = UsingSql.getShiftList();
            DataRow row2 = ShiftList2.NewRow();
            row2["ShiftID"] = 0;
            row2["ShiftName"] = "Không chọn";
            ShiftList2.Rows.Add(row2);
            cbbNV_CaLV2.DataSource = ShiftList2;
            cbbNV_CaLV2.ValueMember = ShiftList2.Columns["ShiftID"].ToString();
            cbbNV_CaLV2.DisplayMember = ShiftList2.Columns["ShiftName"].ToString();
        }

        private void NV_getRoleList()
        {
            DataTable RoleList = UsingSql.getRoleList();
            DataRow row = RoleList.NewRow();
            row[0] = 0;
            row[1] = "Chưa xác định";
            RoleList.Rows.Add(row);
            cbbNV_QuyenHan.DataSource = RoleList;
            cbbNV_QuyenHan.ValueMember = RoleList.Columns["RoleID"].ToString();
            cbbNV_QuyenHan.DisplayMember = RoleList.Columns["RoleName"].ToString();
        }

        private void dhh_datatable_PositionChanged_Employee(object sender, EventArgs e)
        {
            try
            {
                if (bThem_moi == false) NV_Xuat_thong_tin();
            }
            catch (Exception)
            {
            }
        }

        private void btnNV_TaoMoi_Click(object sender, EventArgs e)
        {
            try
            {
                i_select = 1;
                NV_HideAll();
                groupNhanVien.Location = new Point(10, 151);
                groupNhanVien.Size = new Size(437, 473);
                groupNhanVien.Visible = true;
                groupNV_taikhoan.Location = new Point(453, 460);
                groupNV_taikhoan.Size = new Size(267, 164);
                groupNV_taikhoan.Visible = true;
                groupNV_ghichu.Location = new Point(749, 460);
                groupNV_ghichu.Size = new Size(267, 164);
                groupNV_ghichu.Visible = true;
                gvNhanVien.Location = new Point(453, 151);
                gvNhanVien.Size = new Size(563, 266);
                gvNhanVien.Visible = true;
                NV_getDepartmentList();
                NV_getPositionList();
                NV_getShiftList();
                NV_getRoleList();
                NV_Load_Employee();
                NV_EnableTrueAll();
                NV_ResetAll();
                txtNV_MaNV.Text = UsingSql.getEmpIDMax().ToString();
                btnNV_GhiNhan.Text = "Ghi Nhận";
                btnNV_Huy.Text = "Hủy";
                bThem_moi = true;
                gvNhanVien.Enabled = false;
            }
            catch (Exception)
            {
            }
        }

        private void btnNV_DieuChinh_Click(object sender, EventArgs e)
        {
            try
            {
                i_select = 2;
                NV_HideAll();
                NV_Com_HideAll();
                groupNhanVien.Location = new Point(10, 151);
                groupNhanVien.Size = new Size(437, 473);
                groupNhanVien.Visible = true;
                groupNV_taikhoan.Location = new Point(453, 460);
                groupNV_taikhoan.Size = new Size(267, 164);
                groupNV_taikhoan.Visible = true;
                groupNV_ghichu.Location = new Point(749, 460);
                groupNV_ghichu.Size = new Size(267, 164);
                groupNV_ghichu.Visible = true;
                gvNhanVien.Location = new Point(453, 151);
                gvNhanVien.Size = new Size(563, 266);
                gvNhanVien.Visible = true;
                txtNV_Tim.Location = new Point(9, 125);
                txtNV_Tim.Visible = true;
                NV_getDepartmentList();
                NV_getPositionList();
                NV_getShiftList();
                NV_getRoleList();
                NV_EnableFalseAll();
                gvNhanVien.Enabled = true;
                txtNV_Tim.Text = Noi_dung;
                btnNV_GhiNhan.Text = "Chỉnh Sửa";
                btnNV_Huy.Text = "Xóa";
                bThem_moi = false;
                NV_Load_Employee();
            }
            catch (Exception)
            {
            }
        }

        private void btnNV_GhiNhan_Click(object sender, EventArgs e)
        {
            try
            {
                if (i_select == 1)//Tao moi
                {
                    if (btnNV_GhiNhan.Text == "Tạo Mới")
                    {
                        NV_EnableTrueAll();
                        NV_ResetAll();
                        txtNV_MaNV.Text = UsingSql.getEmpIDMax().ToString();
                        btnNV_GhiNhan.Text = "Ghi Nhận";
                        btnNV_Huy.Text = "Hủy";
                        bThem_moi = true;
                        gvNhanVien.Enabled = false;
                    }
                    else
                    {
                        if (NV_Kiem_tra_thong_tin())
                        {
                            Employee emp = NV_Get_thong_tin();
                            if (UsingSql.insert_employee(emp) == 1)
                            {
                                dhh_datatable.AddNew();
                                NV_Nhap_thong_tin(emp);
                                dhh_datatable.EndCurrentEdit();
                                NV_EnableFalseAll();
                                btnNV_GhiNhan.Text = "Tạo Mới";
                                btnNV_Huy.Text = "Hủy";
                                bThem_moi = false;
                                gvNhanVien.Enabled = true;
                            }
                            else
                            {
                                MessageBox.Show("Mã nhân viên đã tồn tại!");
                            }
                        }
                    }
                }
                else//Dieu chinh
                {
                    if (btnNV_GhiNhan.Text == "Chỉnh Sửa")
                    {
                        DataRowView drv = (DataRowView)dhh_datatable.Current;
                        Mat_khau = drv["employeepassword"].ToString();
                        NV_EnableTrueAll();
                        btnNV_GhiNhan.Text = "Ghi Nhận";
                        btnNV_Huy.Text = "Hủy";
                        bThem_moi = false;
                        gvNhanVien.Enabled = false;
                    }
                    else
                    {
                        if (NV_Kiem_tra_thong_tin())
                        {
                            Employee emp = NV_Get_thong_tin();
                            DataRowView drv = (DataRowView)dhh_datatable.Current;
                            emp.EmpID = drv["employeeid"].ToString();
                            if (UsingSql.update_employee(emp) == 1)
                            {
                                NV_Nhap_thong_tin(emp);
                                dhh_datatable.EndCurrentEdit();
                                NV_EnableFalseAll();
                                btnNV_GhiNhan.Text = "Chỉnh Sửa";
                                btnNV_Huy.Text = "Xóa";
                                bThem_moi = false;
                                gvNhanVien.Enabled = true;
                            }
                            else
                            {
                                MessageBox.Show("Mã nhân viên đã tồn tại!!");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void btnNV_Huy_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnNV_Huy.Text == "Hủy")
                {
                    btnNV_GhiNhan.Text = "Chỉnh Sửa";
                    btnNV_Huy.Text = "Xóa";
                    if (i_select == 1)
                    {
                        btnNV_GhiNhan.Text = "Tạo Mới";
                        btnNV_Huy.Text = "Hủy";
                    }
                    NV_EnableFalseAll();
                    gvNhanVien.Enabled = true;
                    bThem_moi = false;
                    NV_Xuat_thong_tin();
                }
                else
                {
                    if (MessageBox.Show("Bạn có muốn xóa thông tin này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        DataRowView drv = (DataRowView)dhh_datatable.Current;
                        int empCode = Convert.ToInt32(drv["employeecode"].ToString());
                        if (UsingSql.delete_employee(empCode) == 1)
                        {
                            dhh_datatable.RemoveAt(dhh_datatable.Position);
                            dhh_datatable.EndCurrentEdit();
                            NV_Xuat_thong_tin();
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void txtNV_Tim_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string tim = txtNV_Tim.Text.Trim();
                string chuoi_tim = "employeecode='" + tim + "'";
                dt_datatable.DefaultView.RowFilter = chuoi_tim;
                if (dt_datatable.DefaultView.Count == 0)
                {
                    chuoi_tim = "employeelastname like '" + tim + "*'";
                    dt_datatable.DefaultView.RowFilter = chuoi_tim;
                }
                NV_Xuat_thong_tin();
            }
            catch (Exception)
            {
            }
        }

        private void txtNV_Tim_Click(object sender, EventArgs e)
        {
            txtNV_Tim.SelectAll();
        }

        private void btnNV_Exit_Click(object sender, EventArgs e)
        {
            NV_HideAll();
        }

        private void cbbNV_CaLV1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void cbbNV_QuyenHan_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (i_select == 1)
            {
                if (cbbNV_QuyenHan.Text != "Chưa xác định")
                {
                    txtNV_TaiKhoan.Enabled = true;
                    txtNV_MatKhau.Enabled = true;
                }
                else
                {
                    txtNV_TaiKhoan.Enabled = false;
                    txtNV_MatKhau.Enabled = false;
                }
            }
        }

        private void txtNV_DienThoai_KeyPress(object sender, KeyPressEventArgs e)
        {
            char keyChar = e.KeyChar;
            e.Handled = !char.IsControl(keyChar) && !char.IsDigit(keyChar);
        }

        private void ckbNV_GioiTinh_Nam_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbNV_GioiTinh_Nam.Checked == true)
                ckbNV_GioiTinh_Nu.Checked = false;
            else
                ckbNV_GioiTinh_Nu.Checked = true;
        }

        private void ckbNV_GioiTinh_Nu_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbNV_GioiTinh_Nu.Checked == true)
                ckbNV_GioiTinh_Nam.Checked = false;
            else
                ckbNV_GioiTinh_Nam.Checked = true;
        }

        private void gvNhanVien_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 4)
            {
                if (e.Value.ToString() == "True")
                    e.Value = "Nam";
                else
                    e.Value = "Nữ";
            }
        }

        #endregion

        #region QUAN LY CHAM CONG

        private void CC_HideAll()
        {
            groupCC_TuyCHon.Visible = false;
            groupCC_KetQua.Visible = false;
            btnCC_XemCT.Enabled = false;
            gvCC_KetQuaLog.Visible = false;
            btnCC_XuatFileExcel.Enabled = false;

        }

        private void CC_Load_Department()
        {
            string sql = "Select DepartmentID,DepartmentName From Department Where Deleted='False'";
            DataTable dt = UsingSql.GetQuery(sql);
            DataRow row = dt.NewRow();
            row[0] = 0;
            row[1] = "CHỌN TẤT CẢ";
            dt.Rows.Add(row);
            comCC_BoPhan.DataSource = dt;
            comCC_BoPhan.DisplayMember = "DepartmentName";
            comCC_BoPhan.ValueMember = "DepartmentID";
        }

        private void CC_Load_Employee()
        {
            string sql = @"Select a.*,b.DepartmentName,c.PositionName,a.EmployeeFirstName +' '+ a.EmployeeLastName As FullName 
                         From Employee a Left Join Department b On a.DepartmentID=b.DepartmentID 
                         Left Join Position c On a.PositionID=c.PositionID Where a.Deleted='False'";
            dt_nhan_vien = UsingSql.GetQuery(sql);
            DataRow row = dt_nhan_vien.NewRow();
            row["EmployeeID"] = "0";
            row["EmployeeCode"] = "0";
            row["DepartmentID"] = 0;
            row["FullName"] = "CHỌN TẤT CẢ";
            dt_nhan_vien.Rows.Add(row);
            comCC_NhanVien.DataSource = dt_nhan_vien;
            comCC_NhanVien.DisplayMember = "FullName";
            comCC_NhanVien.ValueMember = "EmployeeCode";
        }

        private DataTable CC_CreateDatatable()
        {
            DataTable dt = new DataTable();

            DataColumn dc = new DataColumn();
            dc.ColumnName = "MachineNumber";
            dc.DataType = Type.GetType("System.String");
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = "EnrollNumber";
            dc.DataType = Type.GetType("System.String");
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = "Date";
            dc.DataType = Type.GetType("System.String");
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = "DateBegin";
            dc.DataType = Type.GetType("System.DateTime");
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = "DateEnd";
            dc.DataType = Type.GetType("System.DateTime");
            dt.Columns.Add(dc);

            return dt;
        }

        private DataTable CC_Load_All_Data_Log()
        {
            int vTMachineNumber = 0;
            int vSMachineNumber = 0;
            int vSEnrollNumber = 0;
            int vVerifyMode = 0;
            int vYear = 0;
            int vMonth = 0;
            int vDay = 0;
            int vHour = 0;
            int vMinute = 0;
            int vErrorCode = 0;
            int stt = 1;
            string lpszIPAddress = MyServerConfig.SIpAddress;
            bool vRet = false;

            DataTable table = CC_CreateDatatable();

            if (SB100BPC1.ConnectTcpip(gMachineNumber, ref lpszIPAddress, MyServerConfig.SPortNumber, MyServerConfig.SPassWord) == false) return table;

            System.Windows.Forms.Application.DoEvents();

            vRet = SB100BPC1.EnableDevice(mMachineNumber, 0);

            if (vRet == false)
            {
                Cursor = System.Windows.Forms.Cursors.Default;
                return table;
            }

            vRet = SB100BPC1.ReadAllGLogData(mMachineNumber);
            if (vRet == false)
            {
                SB100BPC1.GetLastError(ref vErrorCode);
            }

            if (vRet == true)
            {
                Cursor = System.Windows.Forms.Cursors.WaitCursor;
                System.Windows.Forms.Application.DoEvents();
                while (true)
                {
                    vRet = SB100BPC1.GetAllGLogData(mMachineNumber, ref vTMachineNumber, ref vSEnrollNumber, ref vSMachineNumber, ref vVerifyMode, ref vYear, ref vMonth, ref vDay, ref vHour, ref vMinute);
                    if (vRet == false)
                        break;
                    DateTime date = new DateTime(vYear, vMonth, vDay, vHour, vMinute, 0);
                    DataRow row = table.NewRow();
                    row[0] = stt++.ToString();
                    row[1] = vSEnrollNumber.ToString();
                    row[2] = date.ToString("yyyyMMdd");
                    row[3] = date;
                    row[4] = date;
                    table.Rows.Add(row);
                }
            }
            SB100BPC1.EnableDevice(mMachineNumber, 1);
            return table;
        }

        private DataTable CC_Load_Data_Log_In_Month()
        {
            int month = DateTime.Now.Month;
            int stt = 1;
            DataTable list = CC_Load_All_Data_Log();
            DataTable table = CC_CreateDatatable();
            for (int i = 0; i < list.Rows.Count; i++)
            {
                if (Convert.ToInt32(list.Rows[i]["Date"].ToString().Substring(4, 2)) == month)
                {
                    DataRow row = table.NewRow();
                    row[0] = stt++.ToString();
                    row[1] = list.Rows[i]["EnrollNumber"];
                    row[2] = list.Rows[i]["Date"];
                    row[3] = list.Rows[i]["DateBegin"];
                    row[4] = list.Rows[i]["DateEnd"];
                    table.Rows.Add(row);
                }
            }
            return table;
        }

        private DataTable CC_Load_Data(DateTime beginDate, DateTime endDate)
        {
            int stt = 1;
            DataTable table = CC_Load_All_Data_Log();
            DataTable table_ = new DataTable();
            table_.Columns.Add("STT");
            table_.Columns.Add("EmployeeNo");
            table_.Columns.Add("BeginDate");
            table_.Columns.Add("EndDate");
            beginDate = new DateTime(beginDate.Year, beginDate.Month, beginDate.Day);
            endDate = new DateTime(endDate.Year, endDate.Month, endDate.Day);
            endDate = endDate.AddDays(1);
            foreach (DataRow row in table.Rows)
            {
                DateTime datetmp = Convert.ToDateTime(row["DateBegin"].ToString());
                if (datetmp >= beginDate && datetmp <= endDate)
                {
                    DataRow datarow = table_.NewRow();
                    datarow[0] = stt++.ToString();
                    datarow[1] = row["EnrollNumber"];
                    datarow[2] = row["DateBegin"];
                    datarow[3] = row["DateEnd"];
                    table_.Rows.Add(datarow);
                }
            }
            return table_;
        }

        private DataTable CC_Load_Data_Log()
        {
            int vTMachineNumber = 0;
            int vSMachineNumber = 0;
            int vSEnrollNumber = 0;
            int vVerifyMode = 0;
            int vYear = 0;
            int vMonth = 0;
            int vDay = 0;
            int vHour = 0;
            int vMinute = 0;
            int vErrorCode = 0;
            int stt = 1;
            string lpszIPAddress = MyServerConfig.SIpAddress;
            bool vRet = false;
            DateTime date = DateTime.Now;
            DateTime dateBegin = comCC_NgayTu.Value;
            DateTime dateEnd = comCC_NgayDen.Value;

            dateBegin = new DateTime(dateBegin.Year, dateBegin.Month, dateBegin.Day);
            dateEnd = new DateTime(dateEnd.Year, dateEnd.Month, dateEnd.Day);
            dateEnd = dateEnd.AddDays(1);
            dateEnd = dateEnd.AddSeconds(-1);

            DataTable table = new DataTable();

            DataColumn dc = new DataColumn();
            dc.ColumnName = "STT";
            dc.DataType = Type.GetType("System.String");
            table.Columns.Add(dc);           

            dc = new DataColumn();
            dc.ColumnName = "EmployeeCode";
            dc.DataType = Type.GetType("System.String");
            table.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = "EmployeeName";
            dc.DataType = Type.GetType("System.String");
            table.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = "Date";
            dc.DataType = Type.GetType("System.String");
            table.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = "DateBegin";
            dc.DataType = Type.GetType("System.DateTime");
            table.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = "DateEnd";
            dc.DataType = Type.GetType("System.DateTime");
            table.Columns.Add(dc);

            if (SB100BPC1.ConnectTcpip(gMachineNumber, ref lpszIPAddress, MyServerConfig.SPortNumber, MyServerConfig.SPassWord) == false) return table;

            System.Windows.Forms.Application.DoEvents();

            vRet = SB100BPC1.EnableDevice(mMachineNumber, 0);

            if (vRet == false)
            {
                Cursor = System.Windows.Forms.Cursors.Default;
                return table;
            }

            vRet = SB100BPC1.ReadAllGLogData(mMachineNumber);
            if (vRet == false)
            {
                SB100BPC1.GetLastError(ref vErrorCode);
            }

            if (vRet == true)
            {
                Cursor = System.Windows.Forms.Cursors.WaitCursor;
                System.Windows.Forms.Application.DoEvents();
                while (true)
                {
                    vRet = SB100BPC1.GetAllGLogData(mMachineNumber, ref vTMachineNumber, ref vSEnrollNumber, ref vSMachineNumber, ref vVerifyMode, ref vYear, ref vMonth, ref vDay, ref vHour, ref vMinute);
                    if (vRet == false)
                        break;
                    date = new DateTime(vYear, vMonth, vDay, vHour, vMinute, 0);
                    if (date >= dateBegin && date <= dateEnd)
                    {
                        DataRow row = table.NewRow();
                        row["STT"] = stt++.ToString();
                        row["EmployeeCode"] = vSEnrollNumber.ToString();
                        row["Date"] = date.ToString("yyyyMMdd");
                        row["DateBegin"] = date;
                        row["DateEnd"] = date;
                        table.Rows.Add(row);
                    }
                }
            }
            SB100BPC1.EnableDevice(mMachineNumber, 1);
            Cursor = System.Windows.Forms.Cursors.Default;            
            return table;
        }

        private int CC_Get_RowIndex_Employee(DataView dataview, string EmployeeCode)
        {
            int kq = -1;
            for (int i = 0; i < dataview.Count; i++)
            {
                if (dataview[i]["EmployeeCode"].ToString() == EmployeeCode)
                    return i;
            }
            return kq;
        }

        private int CC_Get_RowIndex(DataTable dt, string manv)
        {
            int kq = -1;
            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                if (dt.Rows[i]["EmployeeCode"].ToString() == manv && dt.Rows[i]["DateEnd"].ToString() == "")
                    return i;
            }
            return kq;
        }

        private int CC_Get_Time_In(DataTable table, DateTime date, ref DateTime dateout)
        {
            int kq = 0;
            if (table.Rows.Count == 0) return kq;
            DateTime timeTemp = DateTime.Now;
            if (table.Rows.Count == 1)
            {
                timeTemp = Convert.ToDateTime(table.Rows[0]["shiftbegin"]);
                timeTemp = new DateTime(date.Year, date.Month, date.Day, timeTemp.Hour, timeTemp.Minute, timeTemp.Second);
                kq = (int)(date - timeTemp).TotalMinutes;
                dateout = Convert.ToDateTime(table.Rows[0]["shiftend"]);
                dateout = new DateTime(date.Year, date.Month, date.Day, dateout.Hour, dateout.Minute, dateout.Second);
            }
            else
            {
                if (Convert.ToDateTime(table.Rows[0]["shiftend"]).Hour < Convert.ToDateTime(table.Rows[1]["shiftend"]).Hour)
                {
                    if (date.Hour < Convert.ToDateTime(table.Rows[0]["shiftend"]).Hour)
                    {
                        timeTemp = Convert.ToDateTime(table.Rows[0]["shiftbegin"]);
                        timeTemp = new DateTime(date.Year, date.Month, date.Day, timeTemp.Hour, timeTemp.Minute, timeTemp.Second);
                        kq = (int)(date - timeTemp).TotalMinutes;
                        dateout = Convert.ToDateTime(table.Rows[0]["shiftend"]);
                        dateout = new DateTime(date.Year, date.Month, date.Day, dateout.Hour, dateout.Minute, dateout.Second);
                    }
                    else
                    {
                        timeTemp = Convert.ToDateTime(table.Rows[1]["shiftbegin"]);
                        timeTemp = new DateTime(date.Year, date.Month, date.Day, timeTemp.Hour, timeTemp.Minute, timeTemp.Second);
                        kq = (int)(date - timeTemp).TotalMinutes;
                        dateout = Convert.ToDateTime(table.Rows[1]["shiftend"]);
                        dateout = new DateTime(date.Year, date.Month, date.Day, dateout.Hour, dateout.Minute, dateout.Second);
                    }
                }
                else
                {
                    if (date.Hour < Convert.ToDateTime(table.Rows[1]["shiftend"]).Hour)
                    {
                        timeTemp = Convert.ToDateTime(table.Rows[1]["shiftbegin"]);
                        timeTemp = new DateTime(date.Year, date.Month, date.Day, timeTemp.Hour, timeTemp.Minute, timeTemp.Second);
                        kq = (int)(date - timeTemp).TotalMinutes;
                        dateout = Convert.ToDateTime(table.Rows[1]["shiftend"]);
                        dateout = new DateTime(date.Year, date.Month, date.Day, dateout.Hour, dateout.Minute, dateout.Second);
                    }
                    else
                    {
                        timeTemp = Convert.ToDateTime(table.Rows[0]["shiftbegin"]);
                        timeTemp = new DateTime(date.Year, date.Month, date.Day, timeTemp.Hour, timeTemp.Minute, timeTemp.Second);
                        kq = (int)(date - timeTemp).TotalMinutes;
                        dateout = Convert.ToDateTime(table.Rows[0]["shiftend"]);
                        dateout = new DateTime(date.Year, date.Month, date.Day, dateout.Hour, dateout.Minute, dateout.Second);
                    }
                }
            }

            if (timeTemp.Hour > dateout.Hour) dateout = dateout.AddDays(1);

            if (kq > 0)
            {
                kq -= UsingSql.latetime;
                if (kq < 0) kq = 0;
            }

            if (Math.Abs(kq) > UsingSql.maxtime)
            {
                if (kq > 0)
                    kq = UsingSql.maxtime;
                else
                    kq = -UsingSql.maxtime;
            }
            return kq;
        }

        private int CC_Get_Time_Out(DataTable table, DateTime timein, DateTime timeout)
        {
            int kq = 0;
            DateTime dateout = DateTime.Now;
            CC_Get_Time_In(table, timein, ref dateout);
            kq = (int)(timeout - dateout).TotalMinutes;
            if (kq < 0)
            {
                kq += UsingSql.earlytime;
                if (kq > 0) kq = 0;
            }
            if (Math.Abs(kq) > UsingSql.maxtime)
            {
                if (kq > 0)
                    kq = UsingSql.maxtime;
                else
                    kq = -UsingSql.maxtime;
            }
            return kq;
        }

        private DataTable CC_Process_Data_Log(DataTable dt)
        {
            int stt = 1;
            int sophut = 0;
            DateTime dtBegin, dtEnd;
            DataTable table = new DataTable();

            table = dt.Clone();
            table.Columns.Add("Total");
            table.Columns.Add("LateIn", Type.GetType("System.Int32"));
            table.Columns.Add("LateOut", Type.GetType("System.Int32"));

            string manv = comCC_NhanVien.SelectedValue.ToString();
            string mabp = comCC_BoPhan.SelectedValue.ToString();
            DataTable empList = UsingSql.getEmpInfo(manv, mabp);
            foreach (DataRow emp in empList.Rows)
            {
                manv = emp["EmployeeCode"].ToString();
                dt.DefaultView.RowFilter = "EmployeeCode='" + manv + "'";
                if (dt.DefaultView.Count > 0)
                {
                    foreach (DataRowView row in dt.DefaultView)
                    {
                        DataTable EmpShift = UsingSql.getEmpShiftInfo(manv);
                        DateTime tmp = DateTime.Now;
                        int idx = CC_Get_RowIndex(table, manv);
                        if (idx == -1)
                        {
                            DataRow datarow = table.NewRow();
                            datarow["STT"] = stt++.ToString();
                            datarow["EmployeeCode"] = row["EmployeeCode"];
                            datarow["EmployeeName"] = UsingSql.getEmpFullName(manv);
                            datarow["Date"] = row["Date"];
                            datarow["DateBegin"] = Convert.ToDateTime(row["DateBegin"]);
                            datarow["LateIn"] = CC_Get_Time_In(EmpShift, Convert.ToDateTime(row["DateBegin"]), ref tmp);
                            table.Rows.Add(datarow);
                        }
                        else
                        {
                            DataRow datarow = table.Rows[idx];
                            dtBegin = Convert.ToDateTime(datarow["DateBegin"]);
                            dtEnd = Convert.ToDateTime(row["DateEnd"]);
                            if (dtBegin.ToString("yyyyMMdd") == dtEnd.ToString("yyyyMMdd"))
                            {
                                sophut = (int)(dtEnd - dtBegin).TotalMinutes;
                                if (sophut > UsingSql.maxtime) sophut = UsingSql.maxtime;
                                if (sophut >= UsingSql.spacetime)
                                {
                                    datarow["EmployeeName"] = UsingSql.getEmpFullName(manv);
                                    datarow["DateEnd"] = dtEnd;
                                    datarow["Total"] = sophut / 60 + "h" + Convert.ToInt32(sophut % 60).ToString("00") + "'";
                                    datarow["LateOut"] = CC_Get_Time_Out(EmpShift, dtBegin, dtEnd);
                                }
                            }
                            else
                            {
                                datarow = table.NewRow();
                                datarow["STT"] = stt++.ToString();
                                datarow["EmployeeCode"] = row["EmployeeCode"];
                                datarow["EmployeeName"] = UsingSql.getEmpFullName(manv);
                                datarow["Date"] = row["Date"];
                                datarow["DateBegin"] = Convert.ToDateTime(row["DateBegin"]);
                                datarow["LateIn"] = CC_Get_Time_In(EmpShift, Convert.ToDateTime(row["DateBegin"]), ref tmp);
                                table.Rows.Add(datarow);
                            }
                        }
                    }
                }
            }

            //foreach (DataRow row in dt.Rows)
            //{
            //    string manv = row["EmployeeCode"].ToString();
            //    //DateTime beginTime = DateTime.Parse(row["DateBegin"].ToString());
            //    DataTable EmpShift = UsingSql.getEmpShiftInfo(manv);
            //    DateTime tmp = DateTime.Now;
            //    int idx = CC_Get_RowIndex(table, manv);
            //    if (idx == -1)
            //    {
            //        DataRow datarow = table.NewRow();
            //        datarow["STT"] = stt++.ToString();
            //        datarow["EmployeeCode"] = row["EmployeeCode"];
            //        datarow["EmployeeName"] = UsingSql.getEmpFullName(manv);
            //        datarow["Date"] = row["Date"];
            //        datarow["DateBegin"] = Convert.ToDateTime(row["DateBegin"]);
            //        datarow["LateIn"] = CC_Get_Time_In(EmpShift, Convert.ToDateTime(row["DateBegin"]), ref tmp);
            //        table.Rows.Add(datarow);
            //    }
            //    else
            //    {
            //        DataRow datarow = table.Rows[idx];
            //        dtBegin = Convert.ToDateTime(datarow["DateBegin"]);
            //        dtEnd = Convert.ToDateTime(row["DateEnd"]);
            //        if (dtBegin.ToString("yyyyMMdd") == dtEnd.ToString("yyyyMMdd"))
            //        {
            //            sophut = (int)(dtEnd - dtBegin).TotalMinutes;
            //            if (sophut > UsingSql.maxtime) sophut = UsingSql.maxtime;
            //            if (sophut >= UsingSql.spacetime)
            //            {
            //                datarow["EmployeeName"] = UsingSql.getEmpFullName(manv);
            //                datarow["DateEnd"] = dtEnd;
            //                datarow["Total"] = sophut / 60 + "h" + Convert.ToInt32(sophut % 60).ToString("00") + "'";
            //                datarow["LateOut"] = CC_Get_Time_Out(EmpShift, dtBegin, dtEnd);
            //            }
            //        }
            //        else
            //        {
            //            datarow = table.NewRow();
            //            datarow["STT"] = stt++.ToString();
            //            datarow["EmployeeCode"] = row["EmployeeCode"];
            //            datarow["EmployeeName"] = UsingSql.getEmpFullName(manv);
            //            datarow["Date"] = row["Date"];
            //            datarow["DateBegin"] = Convert.ToDateTime(row["DateBegin"]);
            //            datarow["LateIn"] = CC_Get_Time_In(EmpShift, Convert.ToDateTime(row["DateBegin"]), ref tmp);
            //            table.Rows.Add(datarow);
            //        }
            //    }
            //}
            table.AcceptChanges();            
            return table;
        }

        private DataTable CC_Process_Data(DataTable dt, DateTime begin, DateTime end)
        {
            DataTable table = new DataTable();
            begin = new DateTime(begin.Year, begin.Month, begin.Day);
            end = new DateTime(end.Year, end.Month, end.Day);
      
            table.Columns.Add("STT");
            table.Columns.Add("EmployeeCode");
            table.Columns.Add("FullName");
            table.Columns.Add("DepartmentName");
            table.Columns.Add("PositionName");
            
            int stt = 1, ica = 0;
            double itong = 0, itong_full = 0;
            int songay = (int)(end.AddDays(1) - begin).TotalDays;
            DateTime dateTemp = begin;
            DateTime dtBegin, dtEnd;
            for (int i = 0; i < songay; i++)
            {
                table.Columns.Add(dateTemp.ToString("dd/MM"));
                dateTemp = dateTemp.AddDays(1);
            }
            table.Columns.Add("Total");
            string mabp = comCC_BoPhan.SelectedValue.ToString();
            string manv = comCC_NhanVien.SelectedValue.ToString();
            DataTable EmpInfo = UsingSql.getEmpInfo(manv, mabp);
            foreach (DataRow dr in EmpInfo.Rows)
            {
                itong_full = 0;
                manv = dr["EmployeeCode"].ToString();                     
                DataTable dt_shift = UsingSql.getEmpShiftInfo(manv);
                ica = UsingSql.getTotalShiftMinutes(dt_shift);
                DataRow row = table.NewRow();
                row[0] = stt++.ToString();
                row[1] = manv;
                row[2] = dr["FullName"].ToString();
                row[3] = dr["DepartmentName"].ToString();
                row[4] = dr["PositionName"].ToString();
                dateTemp = begin;
                for (int i = 0; i < songay; i++)
                {
                    itong = 0;
                    dt.DefaultView.RowFilter = "Date='" + dateTemp.ToString("yyyyMMdd") + "' AND EmployeeCode='" + manv + "'";
                    if (dt.DefaultView.Count >= 1)
                    {
                        for (int j = 0; j < dt.DefaultView.Count; j++)
                        {
                            try
                            {
                                dtBegin = Convert.ToDateTime(dt.DefaultView[j]["DateBegin"]);
                                dtEnd = Convert.ToDateTime(dt.DefaultView[j]["DateEnd"]);
                                itong += (dtEnd - dtBegin).TotalMinutes;
                                if (itong > UsingSql.maxtime) itong = UsingSql.maxtime;
                                //itong = itong / ica;
                            }
                            catch { }
                        }
                        itong_full += itong;
                        //row[5 + i] = Math.Round(itong, 1).ToString();
                        row[5 + i] = CC_DoiPhutSangGio(itong);
                    }
                    if (itong == 0) row[5 + i] = "X";
                    dateTemp = dateTemp.AddDays(1);
                }
                //row[table.Columns.Count - 1] = Math.Round(itong_full, 1).ToString();
                row[table.Columns.Count - 1] = CC_DoiPhutSangGio(itong_full);
                table.Rows.Add(row);
            }
            if (manv == "0")
            {
                int count = table.Rows.Count;
                table.Rows.RemoveAt(count - 1);
            }
            return table;
        }

        private string CC_DoiPhutSangGio(double mins)
        {
            int h = (int)mins / 60;
            int m = (int)mins % 60;
            string kq = h.ToString() + "h" + m.ToString("00") + "'";
            return kq;
        }

        private void riQL_ChamCong_Click(object sender, EventArgs e)
        {
            CC_HideAll();
        }

        private void btnCC_BaoCao_Click(object sender, EventArgs e)
        {
            try
            {
                CC_HideAll();
                groupCC_TuyCHon.Location = new Point(10, 125);
                groupCC_TuyCHon.Size = new Size(271, 496);
                groupCC_TuyCHon.Visible = true;
                groupCC_KetQua.Location = new Point(287, 125);
                groupCC_KetQua.Size = new Size(725, 496);
                groupCC_KetQua.Visible = true;
                btnCC_Xem.Enabled = false;
                btnCC_XemCT.Enabled = false;
                CC_Load_Department();
                CC_Load_Employee();
                comCC_BoPhan_SelectedIndexChanged(sender, e);
            }
            catch (Exception)
            {
            }
        }

        private void comCC_BoPhan_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string DepartmentID = comCC_BoPhan.SelectedValue.ToString();
                dt_nhan_vien.DefaultView.RowFilter = "DepartmentID In (0," + DepartmentID + ")";
                if (DepartmentID == "0")
                    dt_nhan_vien.DefaultView.RowFilter = "1=1";
                if (dt_nhan_vien.DefaultView.Count == 1)
                    dt_nhan_vien.DefaultView.RowFilter = "1=0";
                btnCC_XemCT.Enabled = false;
                gvCC_KetQua.DataSource = null;
            }
            catch (Exception)
            {
            }
        }

        private void btnCC_XemCT_Click(object sender, EventArgs e)
        {
            try
            {
                dt_data_log.DefaultView.RowFilter = "EmployeeCode is not null";
                dt_data_log.DefaultView.Sort = "EmployeeCode Asc";
                gvCC_KetQua.Visible = false;
                gvCC_KetQuaLog.Visible = true;                
                btnCC_XemCT.Enabled = false;
            }
            catch (Exception)
            {
            }
        }

        private void btnCC_TaiDuLieu_Click(object sender, EventArgs e)
        {
            if (cc_kiemtra(comCC_NgayTu.Value, comCC_NgayDen.Value))
            {
                if (btnCC_TaiDuLieu.Text == "TẢI DỮ LIỆU")
                {
                    dt_data = CC_Load_Data_Log();
                    btnCC_Xem.Enabled = true;
                    btnCC_XemCT.Enabled = true;
                    comCC_NgayTu.Enabled = false;
                    comCC_NgayDen.Enabled = false;
                    btnCC_TaiDuLieu.Text = "TẢI LẠI";
                }
                else
                {
                    dt_data = null;
                    dt_datatable = null;
                    dt_data_log = null;
                    dhh_datatable = null;
                    btnCC_Xem.Enabled = false;
                    btnCC_XemCT.Enabled = false;
                    btnCC_XuatFileExcel.Enabled = false;
                    comCC_NgayTu.Enabled = true;
                    comCC_NgayDen.Enabled = true;
                    btnCC_TaiDuLieu.Text = "TẢI DỮ LIỆU";
                }
            }
        }

        private bool cc_kiemtra(DateTime dtbegin, DateTime dtend)
        {
            dtbegin = new DateTime(dtbegin.Year, dtbegin.Month, dtbegin.Day);
            dtend = new DateTime(dtend.Year, dtend.Month, dtend.Day);
            if (!(dtbegin.Year == dtend.Year && dtbegin.Month < dtend.Month && dtbegin.Day >= dtend.Day)&&
                !(dtbegin.Year == dtend.Year && dtbegin.Month == dtend.Month && dtbegin.Day <= dtend.Day))
            {                
                MessageBox.Show("Bạn chỉ xem thông kê 1 tháng.");
                return false;
            }
            return true;
        }

        private void btnCC_Xem_Click(object sender, EventArgs e)
        {
            try
            {
                //if (gvCC_KetQuaLog.Visible)
                //{
                //    gvCC_KetQua.Visible = true;
                //    gvCC_KetQuaLog.Visible = false;
                //    btnCC_XemCT.Enabled = true;
                //    btnCC_XuatFileExcel.Enabled = true;
                //}
                //else
                //{
                    gvCC_KetQua.DataSource = null;
                    Cursor = System.Windows.Forms.Cursors.WaitCursor;
                    //DataTable dt = CC_Load_Data_Log();
                    dt_data_log = CC_Process_Data_Log(dt_data);
                    dt_datatable = CC_Process_Data(dt_data_log, comCC_NgayTu.Value, comCC_NgayDen.Value);
                    dhh_datatable = BindingContext[dt_datatable];
                    gvCC_KetQua.DataSource = dt_datatable;
                    gvCC_KetQuaLog.AutoGenerateColumns = false;
                    gvCC_KetQuaLog.DataSource = dt_data_log;
                    Cursor = System.Windows.Forms.Cursors.Default;
                    btnCC_XemCT.Enabled = true;
                    gvCC_KetQua.Visible = true;
                    gvCC_KetQuaLog.Visible = false;
                    btnCC_XuatFileExcel.Enabled = true;
                    gvCC_KetQua.Columns[2].Frozen = true;
                    gvCC_KetQua.Columns[1].HeaderText = "MÃ NV";
                    gvCC_KetQua.Columns[2].HeaderText = "TÊN NHÂN VIÊN";
                    gvCC_KetQua.Columns[3].HeaderText = "TÊN BỘ PHẬN";
                    gvCC_KetQua.Columns[4].HeaderText = "TÊN CHỨC VỤ";
                    gvCC_KetQua.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
                //}
            }
            catch (Exception)
            {
                Cursor = System.Windows.Forms.Cursors.Default;
            }
        }

        private void Excel_TongHop(DataView view)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            Excel.Range chartRange;
            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            try
            {
                string[] cols = getExcelColumn(view.Table.Columns.Count);
                int rowIndex = 1;
                for (int i = 0; i < view.Table.Columns.Count; i++)
                {
                    chartRange = xlWorkSheet.get_Range(cols[i] + (rowIndex).ToString(), cols[i] + (rowIndex).ToString());
                    chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                    chartRange.Font.Name = "Times New Roman";
                    chartRange.Font.Size = 12;
                    chartRange.Font.Bold = true;
                    chartRange.HorizontalAlignment = 3;
                    chartRange.VerticalAlignment = 3;
                    if (i > 4 && i < view.Table.Columns.Count - 1)
                    {
                        chartRange.Formula = view.Table.Columns[i].ColumnName.ToString().Replace('/', 'T');
                    }
                    else
                    {
                        if (i == 0)
                        {
                            chartRange.Formula = "STT";
                        }
                        else if (i == 1)
                        {
                            chartRange.Formula = "MNV";
                        }
                        else if (i == 2)
                        {
                            chartRange.Formula = "NHÂN VIÊN";
                        }
                        else if (i == 3)
                        {
                            chartRange.Formula = "BỘ PHẬN";
                        }
                        else if (i == 4)
                        {
                            chartRange.Formula = "CHỨC VỤ";
                        }
                        else
                        {
                            chartRange.Formula = "TỔNG";
                        }
                    }
                }
                Start_ProcessBar(view);
                foreach (DataRowView row in view)
                {
                    Load_ProcessBar(1);
                    rowIndex++;
                    for (int j = 0; j < cols.Length; j++)
                    {
                        chartRange = xlWorkSheet.get_Range(cols[j] + rowIndex.ToString(), cols[j] + rowIndex.ToString());
                        chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                        chartRange.Font.Name = "Times New Roman";
                        chartRange.Font.Size = 10;
                        chartRange.HorizontalAlignment = 3;
                        chartRange.VerticalAlignment = 3;
                        chartRange.EntireColumn.AutoFit();
                        chartRange.EntireRow.AutoFit();
                        chartRange.Formula = row[j].ToString();
                        if (j > 4 && j < view.Table.Columns.Count - 1)
                        {
                            try
                            {
                                double k = Convert.ToDouble(row[j]);
                                if (k < 0.5)//mau vang
                                {
                                    chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Yellow);
                                }
                                else if (k < 1)//xanh la cay
                                {
                                    chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Green);
                                }
                                else if (k == 1)//mau do
                                {
                                    chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Red);
                                }
                                else//mau xanh duong
                                {
                                    chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Blue);
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
                End_ProcessBar();
                xlApp.Visible = true;
            }
            catch (Exception)
            {
            }
        }

        private void Excel_ThongKe(DataView view)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            Excel.Range chartRange;
            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            int ngay = (int)(comCC_NgayDen.Value - comCC_NgayTu.Value).TotalDays+1;
            int socot = 5 + ngay*2+1;
            try
            {                
                string[] cols = getExcelColumn(socot);
                DataColumnCollection colsName = view.Table.Columns;

                int colsNameIndex = 5;
                int rowIndex = 1;
                int count = 0;

                xlWorkSheet.get_Range(cols[0] + (rowIndex).ToString(), cols[cols.Length - 1] + (4).ToString()).Merge(false);
                chartRange = xlWorkSheet.get_Range(cols[0] + (rowIndex).ToString(), cols[cols.Length-1] + (rowIndex).ToString());
                chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 12;
                chartRange.Font.Bold = true;
                chartRange.Formula = "THỐNG KÊ CHẤM CÔNG" + " THÁNG " + comCC_NgayTu.Value.Month.ToString();
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 2;

                rowIndex=5;

                for (int i = 0; i < view.Table.Columns.Count; i++)
                {                    
                    if (i > 4 && i < view.Table.Columns.Count - 1)
                    {
                        xlWorkSheet.get_Range(cols[count] + (rowIndex).ToString(), cols[count+1] + (rowIndex).ToString()).Merge(false);
                        chartRange = xlWorkSheet.get_Range(cols[count] + (rowIndex).ToString(), cols[count+1] + (rowIndex).ToString());
                        chartRange.Formula = colsName[colsNameIndex++].ColumnName.ToString().Substring(0, 2);
                        chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                        chartRange.Font.Name = "Times New Roman";
                        chartRange.Font.Size = 12;
                        chartRange.Font.Bold = true;
                        chartRange.HorizontalAlignment = 3;
                        chartRange.VerticalAlignment = 2;
                        chartRange.ColumnWidth = 10;

                        chartRange = xlWorkSheet.get_Range(cols[count] + (rowIndex + 1).ToString(), cols[count] + (rowIndex + 1).ToString());
                        chartRange.Formula = "In";
                        chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                        chartRange.Font.Name = "Times New Roman";
                        chartRange.Font.Size = 12;
                        chartRange.Font.Bold = true;
                        chartRange.HorizontalAlignment = 3;
                        chartRange.VerticalAlignment = 2;
                        chartRange.ColumnWidth = 5;

                        chartRange = xlWorkSheet.get_Range(cols[count+1] + (rowIndex + 1).ToString(), cols[count+1] + (rowIndex + 1).ToString());
                        chartRange.Formula = "Out";
                        chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                        chartRange.Font.Name = "Times New Roman";
                        chartRange.Font.Size = 12;
                        chartRange.Font.Bold = true;
                        chartRange.HorizontalAlignment = 3;
                        chartRange.VerticalAlignment = 2;
                        chartRange.ColumnWidth = 5;

                        count=count+2;
                    }
                    else
                    {
                        xlWorkSheet.get_Range(cols[count] + (rowIndex).ToString(), cols[count] + (rowIndex + 1).ToString()).Merge(false);
                        chartRange = xlWorkSheet.get_Range(cols[count] + (rowIndex).ToString(), cols[count] + (rowIndex + 1).ToString());
                        chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                        chartRange.Font.Name = "Times New Roman";
                        chartRange.Font.Size = 12;
                        chartRange.Font.Bold = true;
                        chartRange.HorizontalAlignment = 3;
                        chartRange.VerticalAlignment = 2;
                        if (i == 0)
                        {
                            chartRange.Formula = "STT";
                        }
                        else if (i == 1)
                        {
                            chartRange.Formula = "MNV";
                        }
                        else if (i == 2)
                        {
                            chartRange.Formula = "HỌ TÊN";
                        }
                        else if (i == 3)
                        {
                            chartRange.Formula = "BỘ PHẬN";
                        }
                        else if (i == 4)
                        {
                            chartRange.Formula = "CHỨC VỤ";
                        }
                        else
                        {
                            chartRange.Formula = "GHI CHÚ";
                        }
                        count++;
                    }
                }
                
                Start_ProcessBar(view);
                rowIndex = rowIndex + 2;
                foreach (DataRow row in view.Table.Rows)
                {
                    count = 0;
                    for (count = 0; count < socot; count++)
                    {
                        if (count < 5)
                        {
                            chartRange = xlWorkSheet.get_Range(cols[count] + rowIndex.ToString(), cols[count] + rowIndex.ToString());
                            chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                            chartRange.Font.Name = "Times New Roman";
                            chartRange.Font.Size = 10;
                            chartRange.HorizontalAlignment = 3;
                            chartRange.VerticalAlignment = 3;
                            chartRange.EntireColumn.AutoFit();
                            chartRange.EntireRow.AutoFit();
                            chartRange.Formula = row[count].ToString();
                            //count++;
                        }
                        else
                        {
                            //string bDay = comCC_NgayTu.Value.ToString("yyyyMMdd");
                            int? oldDay = null;
                            int? oldcount = null;
                            int startIndex = rowIndex;
                            int oldrowIndex = rowIndex;
                            DataRow[] datarowArr = dt_data_log.Select("EmployeeCode='" + row["EmployeeCode"].ToString() + "'","DateBegin ASC");
                            if (datarowArr.Length == 0)
                            {
                                rowIndex++;
                                break;
                            }
                            foreach (DataRow dtrow in datarowArr)
                            {
                                DateTime time = Convert.ToDateTime(dtrow["DateBegin"].ToString());
                                int beginDay = comCC_NgayTu.Value.Day;
                                int currentDay = time.Day;
                                if (count == 5)
                                {
                                    count += (currentDay - beginDay) * 2;
                                }
                                if (oldDay == null)
                                    oldDay = currentDay;
                                if (oldcount == null)
                                    oldcount = count;
                                if (oldDay == currentDay)
                                {
                                    //count = 5;
                                    count = oldcount.Value;
                                    for (int j = 4; j <= 5; j++)
                                    {
                                        chartRange = xlWorkSheet.get_Range(cols[count] + rowIndex.ToString(), cols[count] + rowIndex.ToString());
                                        chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                                        chartRange.Font.Name = "Times New Roman";
                                        chartRange.Font.Size = 10;
                                        chartRange.HorizontalAlignment = 3;
                                        chartRange.VerticalAlignment = 3;
                                        chartRange.ColumnWidth = 5;
                                        try
                                        {
                                            string a = Convert.ToDateTime(dtrow[j].ToString()).ToString("HH:mm");
                                            chartRange.Formula = a;
                                        }
                                        catch
                                        {
                                            chartRange.Formula = "X";
                                        }
                                        count++;
                                    }
                                    oldrowIndex = startIndex;
                                    rowIndex++;
                                }
                                else
                                {
                                    rowIndex = oldrowIndex + 1;
                                    if (currentDay - oldDay.Value > 0)
                                    {
                                        int a = (currentDay - (oldDay.Value + 1)) * 2;
                                        count = count + a;
                                        oldcount = count;
                                    }
                                    for (int j = 4; j <= 5; j++)
                                    {
                                        if (startIndex != oldrowIndex)
                                        {
                                            chartRange = xlWorkSheet.get_Range(cols[count] + oldrowIndex.ToString(), cols[count] + oldrowIndex.ToString());
                                            chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                                            chartRange.Font.Name = "Times New Roman";
                                            chartRange.Font.Size = 10;
                                            chartRange.HorizontalAlignment = 3;
                                            chartRange.VerticalAlignment = 3;
                                            chartRange.ColumnWidth = 5;                                        
                                        }
                                        else
                                        {
                                            chartRange = xlWorkSheet.get_Range(cols[count] + startIndex.ToString(), cols[count] + startIndex.ToString());
                                            chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                                            chartRange.Font.Name = "Times New Roman";
                                            chartRange.Font.Size = 10;
                                            chartRange.HorizontalAlignment = 3;
                                            chartRange.VerticalAlignment = 3;
                                            chartRange.ColumnWidth = 5;    
                                            //rowIndex++;
                                        }
                                        try
                                        {
                                            string a = Convert.ToDateTime(dtrow[j].ToString()).ToString("HH:mm");
                                            chartRange.Formula = a;
                                        }
                                        catch
                                        {
                                            chartRange.Formula = "X";
                                        }
                                        //oldcount = count++;
                                        count++;
                                    }
                                    //rowIndex = oldrowIndex + 1;
                                    oldDay = currentDay;
                                    //oldcount = count;
                                }
                                if (datarowArr.Last() == dtrow)
                                {
                                    count = socot;
                                    rowIndex++;
                                }
                            }
                        }
                    }
                    Load_ProcessBar(1);
                }
                chartRange = xlWorkSheet.get_Range(cols[0] + 1.ToString(), cols[socot-1] + (rowIndex-1).ToString());
                Excel.Borders borders = chartRange.Borders;
                borders.Value = Excel.XlBordersIndex.xlDiagonalDown;
                borders.LineStyle = Excel.XlLineStyle.xlContinuous;
                borders.Weight = Excel.XlBorderWeight.xlThin;
                borders.ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
                chartRange.Cells.AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1, false, true, true, borders, true, true);
                
                End_ProcessBar();
                xlApp.Visible = true;
            }
            catch (Exception)
            {
                End_ProcessBar();
                xlApp.Visible = true;
            }
        }

        private void Excel_ChiTiet(DataView view)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            Excel.Range chartRange;
            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            try
            {
                int colIndex = 0;
                int rowIndex = 1;
                int stt = 0;

                xlWorkSheet.get_Range("A1", "J4").Merge(false);
                chartRange = xlWorkSheet.get_Range("A1", "J4");
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 14;
                chartRange.Font.Bold = true;
                chartRange.Formula = "THỐNG KÊ CHẤM CÔNG";
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 2;

                rowIndex = 5;

                chartRange = xlWorkSheet.get_Range("A" + (rowIndex).ToString(), "A" + (rowIndex).ToString());
                chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 12;
                chartRange.Font.Bold = true;
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 3;
                chartRange.Formula = "STT";

                chartRange = xlWorkSheet.get_Range("B" + (rowIndex).ToString(), "B" + (rowIndex).ToString());
                chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 12;
                chartRange.Font.Bold = true;
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 3;
                chartRange.Formula = "MNV";

                chartRange = xlWorkSheet.get_Range("C" + (rowIndex).ToString(), "C" + (rowIndex).ToString());
                chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 12;
                chartRange.Font.Bold = true;
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 3;
                chartRange.Formula = "NHÂN VIÊN";

                chartRange = xlWorkSheet.get_Range("D" + (rowIndex).ToString(), "D" + (rowIndex).ToString());
                chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 12;
                chartRange.Font.Bold = true;
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 3;
                chartRange.Formula = "THỜI GIAN VÀO";

                chartRange = xlWorkSheet.get_Range("E" + (rowIndex).ToString(), "E" + (rowIndex).ToString());
                chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 12;
                chartRange.Font.Bold = true;
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 3;
                chartRange.Formula = "THỜI GIAN RA";

                chartRange = xlWorkSheet.get_Range("F" + (rowIndex).ToString(), "F" + (rowIndex).ToString());
                chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 12;
                chartRange.Font.Bold = true;
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 3;
                chartRange.Formula = "SỐ GIỜ";

                chartRange = xlWorkSheet.get_Range("G" + (rowIndex).ToString(), "G" + (rowIndex).ToString());
                chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 12;
                chartRange.Font.Bold = true;
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 3;
                chartRange.Formula = "VÀO SỚM";

                chartRange = xlWorkSheet.get_Range("H" + (rowIndex).ToString(), "H" + (rowIndex).ToString());
                chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 12;
                chartRange.Font.Bold = true;
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 3;
                chartRange.Formula = "VÀO TRỄ";

                chartRange = xlWorkSheet.get_Range("I" + (rowIndex).ToString(), "I" + (rowIndex).ToString());
                chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 12;
                chartRange.Font.Bold = true;
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 3;
                chartRange.Formula = "RA SỚM";

                chartRange = xlWorkSheet.get_Range("J" + (rowIndex).ToString(), "J" + (rowIndex).ToString());
                chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                chartRange.Font.Name = "Times New Roman";
                chartRange.Font.Size = 12;
                chartRange.Font.Bold = true;
                chartRange.HorizontalAlignment = 3;
                chartRange.VerticalAlignment = 3;
                chartRange.Formula = "RA TRỄ";

                string[] colum = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
                Start_ProcessBar(view);
                foreach (DataRowView row in view)
                {
                    Load_ProcessBar(1);
                    rowIndex++;
                    colIndex = -1;
                    stt++;
                    for (int i = 0; i < colum.Length; i++)
                    {
                        colIndex++;

                        string Range = colum[i].ToString() + rowIndex.ToString();
                        chartRange = xlWorkSheet.get_Range(Range, Range);
                        try
                        {
                            if (colum[i].ToString() == "A")//stt
                            {
                                chartRange.Formula = stt.ToString();
                            }
                            else if (colum[i].ToString() == "B")
                            {
                                chartRange.Formula = row["employeecode"].ToString();
                            }
                            else if (colum[i].ToString() == "C")
                            {
                                chartRange.Formula = UsingSql.getEmpFullName(row["employeecode"].ToString());
                            }
                            else if (colum[i].ToString() == "D")//thoi gian vao
                            {
                                chartRange.Formula = Convert.ToDateTime(row["datebegin"]).ToString("dd/MM/yyyy HH:mm");
                            }
                            else if (colum[i].ToString() == "E")//thoi gian ra
                            {
                                chartRange.Formula = Convert.ToDateTime(row["dateend"]).ToString("dd/MM/yyyy HH:mm");
                            }
                            else if (colum[i].ToString() == "F")//thoi gian lam viec
                            {
                                chartRange.Formula = row["total"].ToString();
                            }
                            else if (colum[i].ToString() == "G")//vao som
                            {
                                int latein = Convert.ToInt32(row["latein"]);
                                string sogio;
                                if (latein < 0)
                                {
                                    latein = Math.Abs(latein);
                                    sogio = latein / 60 + "h" + Convert.ToInt32(latein % 60).ToString("00") + "'";
                                    chartRange.Formula = sogio;
                                    chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Yellow);
                                }
                            }
                            else if (colum[i].ToString() == "H")//vao tre
                            {
                                int latein = Convert.ToInt32(row["latein"]);
                                string sogio;
                                if (latein > 0)
                                {
                                    sogio = latein / 60 + "h" + Convert.ToInt32(latein % 60).ToString("00") + "'";
                                    chartRange.Formula = sogio;
                                    chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Red);
                                }
                            }
                            else if (colum[i].ToString() == "I")//ra som
                            {
                                int lateout = Convert.ToInt32(row["lateout"]);
                                string sogio;
                                if (lateout < 0)
                                {
                                    lateout = Math.Abs(lateout);
                                    sogio = lateout / 60 + "h" + Convert.ToInt32(lateout % 60).ToString("00") + "'";
                                    chartRange.Formula = sogio;
                                    chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Blue);

                                }
                            }
                            else if (colum[i].ToString() == "J")//ra tre
                            {
                                int lateout = Convert.ToInt32(row["lateout"]);
                                string sogio;
                                if (lateout > 0)
                                {
                                    lateout = Math.Abs(lateout);
                                    sogio = lateout / 60 + "h" + Convert.ToInt32(lateout % 60).ToString("00") + "'";
                                    chartRange.Formula = sogio;
                                    chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Green);

                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                        chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                        chartRange.Font.Name = "Times New Roman";
                        chartRange.Font.Size = 11;
                        chartRange.HorizontalAlignment = 3;
                        chartRange.VerticalAlignment = 3;
                        if (colum[i].ToString() == "C") chartRange.HorizontalAlignment = 2;
                        chartRange.EntireColumn.AutoFit();
                        chartRange.EntireRow.AutoFit();
                    }
                }
                End_ProcessBar();
                xlApp.Visible = true;
            }
            catch (Exception)
            {
            }
        }

        private void btnCC_XuatFileExcel_Click(object sender, EventArgs e)
        {
            if (gvCC_KetQua.Visible)
            {
                Excel_TongHop(dt_datatable.DefaultView);
            }
            else
            {
                Excel_ChiTiet(dt_data_log.DefaultView);
            }
        }

        private string[] getExcelColumn(int colCount)
        {
            string[] alphabet = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".Split(' ');
            string[] cols = new string[colCount];
            string a = string.Empty;
            int count = 0;
            try
            {
                while (count < colCount)
                {
                    for (int i = -1; i < alphabet.Length; i++)
                    {
                        if (i < 0)
                        {
                            for (int j = 0; j < alphabet.Length; j++)
                            {
                                cols[count] = alphabet[j];
                                count++;
                            }
                        }
                        else
                        {
                            a = alphabet[i];
                            for (int k = 0; k < alphabet.Length; k++)
                            {
                                cols[count] = a + alphabet[k];
                                count++;
                            }
                        }
                    }
                }
                return cols;
            }
            catch
            {
                return cols;
            }
        }

        private void btnCC_Excel_DiSom_Click(object sender, EventArgs e)
        {
            dt_data_log.DefaultView.RowFilter = "LateIn is not Null and LateIn<0";
            Excel_ChiTiet(dt_data_log.DefaultView);
        }

        private void btnCC_Excel_DiTre_Click(object sender, EventArgs e)
        {
            dt_data_log.DefaultView.RowFilter = "LateIn is not Null and LateIn>0";
            Excel_ChiTiet(dt_data_log.DefaultView);
        }

        private void btnCC_Excel_VeSom_Click(object sender, EventArgs e)
        {
            dt_data_log.DefaultView.RowFilter = "LateOut is not Null and LateOut<0";
            Excel_ChiTiet(dt_data_log.DefaultView);
        }

        private void btnCC_Excel_VeTre_Click(object sender, EventArgs e)
        {
            dt_data_log.DefaultView.RowFilter = "LateOut is not Null and LateOut>0";
            Excel_ChiTiet(dt_data_log.DefaultView);
        }

        private void btnCC_Excel_ThongKe_Click(object sender, EventArgs e)
        {
            Excel_ThongKe(dt_datatable.DefaultView);
        }

        private void comCC_NhanVien_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnCC_XemCT.Enabled = false;
        }

        private void Start_ProcessBar(DataView view)
        {
            xuly.Visible = true;
            xuly.Maximum = view.Count;
        }

        private void Load_ProcessBar(int value)
        {
            xuly.Text = "Loading...";
            xuly.Value += value;
            xuly.Refresh();
        }

        private void End_ProcessBar()
        {
            xuly.Text = "Completed";
            xuly.Visible = false;
        }

        #endregion

        #region QUAN LY HE THONG
        private void HT_HideAll()
        {
            groupHeThong.Visible = false;
        }

        private void HT_EnableTrueAll()
        {
            txtHT_SpaceTime.Enabled = true;
            txtHT_LateTime.Enabled = true;
            txtHT_EarlyTime.Enabled = true;
            txtHT_MaxTime.Enabled = true;
            txtHT_MonthBegin.Enabled = true;
            cbHT_LogTime.Enabled = true;
        }

        private void HT_EnableFalseAll()
        {
            txtHT_SpaceTime.Enabled = false;
            txtHT_LateTime.Enabled = false;
            txtHT_EarlyTime.Enabled = false;
            txtHT_MaxTime.Enabled = false;
            txtHT_MonthBegin.Enabled = false;
            cbHT_LogTime.Enabled = false;
        }

        private void HT_Load_Set()
        {
            dt_datatable = UsingSql.GetSetList();
            if (dt_datatable != null && dt_datatable.Rows.Count > 0)
            {
                setID = dt_datatable.Rows[0][0].ToString();
                txtHT_SpaceTime.Text = dt_datatable.Rows[0]["SpaceTime"].ToString();
                txtHT_LateTime.Text = dt_datatable.Rows[0]["LateTime"].ToString();
                txtHT_EarlyTime.Text = dt_datatable.Rows[0]["EarlyTime"].ToString();
                txtHT_MaxTime.Text = dt_datatable.Rows[0]["MaxTime"].ToString();
                txtHT_MonthBegin.Text = dt_datatable.Rows[0]["MonthBegin"].ToString();
                cbHT_LogTime.Checked = Convert.ToBoolean(dt_datatable.Rows[0]["LogTime"].ToString());
            }
        }

        private bool HT_Kiem_tra_thong_tin()
        {
            if (txtHT_SpaceTime.Text == string.Empty ||
                txtHT_LateTime.Text == string.Empty ||
                txtHT_EarlyTime.Text == string.Empty ||
                txtHT_MaxTime.Text == string.Empty ||
                txtHT_MonthBegin.Text == string.Empty)
            {
                MessageBox.Show("Nhập đầy đủ thông tin");
                return false;
            }
            return true;
        }

        private Set HT_Get_thong_tin()
        {
            Set s = new Set();
            s.SetID = Convert.ToInt32(setID);
            s.SpaceTime = Convert.ToInt32(txtHT_SpaceTime.Text.Trim());
            s.LateTime = Convert.ToInt32(txtHT_LateTime.Text.Trim());
            s.EarlyTime = Convert.ToInt32(txtHT_EarlyTime.Text.Trim());
            s.MaxTime = Convert.ToInt32(txtHT_MaxTime.Text.Trim());
            s.MonthBegin = Convert.ToInt32(txtHT_MonthBegin.Text.Trim());
            s.LogTime = cbHT_LogTime.Checked;
            return s;
        }

        private void riQL_HeThong_Click(object sender, EventArgs e)
        {
            groupHeThong.Visible = true;
            HT_HideAll();
            HT_EnableFalseAll();
            HT_Load_Set();
            btnHT_GhiNhan.Text = "Chỉnh sửa";
        }

        private void btnHT_GhiNhan_Click(object sender, EventArgs e)
        {
            if (btnHT_GhiNhan.Text == "Chỉnh sửa")
            {
                HT_EnableTrueAll();
                btnHT_GhiNhan.Text = "Ghi nhận";
                btnHT_Huy.Enabled = true;
            }
            else
            {
                if (HT_Kiem_tra_thong_tin())
                {
                    Set s = HT_Get_thong_tin();
                    if (UsingSql.update_Set(s) == 1)
                    {
                        HT_EnableFalseAll();
                        btnHT_GhiNhan.Text = "Chỉnh sửa";
                        btnHT_Huy.Enabled = false;
                    }
                }
                else
                {
                    MessageBox.Show("Thông tin không hợp lệ");
                }
            }
        }

        private void btnHT_Huy_Click(object sender, EventArgs e)
        {
            HT_EnableFalseAll();
            HT_Load_Set();
            btnHT_GhiNhan.Text = "Chỉnh sửa";
            btnHT_Huy.Enabled = false;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            groupHeThong.Visible = true;
            btnHT_Huy.Enabled = false;
        }
        #endregion

        #region QUAN LY COM

        private void NV_Com_HideAll()
        {
            txtCom_Tim.Visible = false;
            groupCom_ThoiGian.Visible = false;
            groupCom_ThongTin.Visible = false;
            dgvCom_DanhSach.Visible = false;
        }

        private void NV_Com_ShowAll()
        {
            groupCom_ThoiGian.Location = new Point(10, 126);
            groupCom_ThoiGian.Size = new Size(337, 111);
            groupCom_ThoiGian.Visible = true;
            groupCom_ThongTin.Location = new Point(10, 280);
            groupCom_ThongTin.Size = new Size(337, 350);
            groupCom_ThongTin.Visible = true;
            dgvCom_DanhSach.Location = new Point(353, 151);
            dgvCom_DanhSach.Size = new Size(663, 303);
            dgvCom_DanhSach.Visible = true;
            txtCom_Tim.Location = new Point(10, 250);
            txtCom_Tim.Size = new Size(338, 26);
            txtCom_Tim.Visible = true;
            dtiCom_TuNgay.Value = DateTime.Now;
            dtiCom_DenNgay.Value = DateTime.Now;
            dtiCom_Ngay.Value = DateTime.Now;
        }

        private void NV_Com_EnableFalseAll()
        {
            //txtCom_Tim.Enabled = false;
            lbox_Com_NhanVien_BoPhan.Enabled = false;
            dtiCom_Ngay.Enabled = false;
            rbtnCom_BoPhan.Enabled = false;
            rbtnCom_NhanVien.Enabled = false;
            txtCom_GhiChu.Enabled = false;
            btnCom_GhiNhan.Enabled = false;
        }

        private void NV_Com_EnableTrueAll()
        {
            lbox_Com_NhanVien_BoPhan.Enabled = true;
            dtiCom_Ngay.Enabled = true;
            rbtnCom_BoPhan.Enabled = true;
            rbtnCom_NhanVien.Enabled = true;
            txtCom_GhiChu.Enabled = true;
            btnCom_GhiNhan.Enabled = true;
        }

        private void btnNV_DKCom_Click(object sender, EventArgs e)
        {
            try
            {
                NV_HideAll();
                NV_Com_HideAll();
                NV_Com_ShowAll();
                NV_Com_EnableFalseAll();
                rbtnCom_NhanVien.Checked = true;
                btnCom_GhiNhan.Text = "Tạo Mới";
                txtCom_Tim.Text = Noi_dung;
                lbox_Com_NhanVien_BoPhan.SelectionMode = SelectionMode.One;
                NV_Com_Load_AllEmpRice();
            }
            catch (Exception)
            {
            }
        }

        private void btnCom_Xem_Click(object sender, EventArgs e)
        {
            try
            {
                txtCom_Tim.Enabled = true;
                DateTime dateBegin = dtiCom_TuNgay.Value;
                DateTime dateEnd = dtiCom_DenNgay.Value;
                dateBegin = new DateTime(dateBegin.Year, dateBegin.Month, dateBegin.Day);
                dateEnd = new DateTime(dateEnd.Year, dateEnd.Month, dateEnd.Day);
                dateEnd = dateEnd.AddDays(1);
                dateEnd = dateEnd.AddSeconds(-1);
                dt_datatable = UsingSql.GetEmpRiceList(dateBegin, dateEnd);
                dhh_datatable = BindingContext[dt_datatable];
                dhh_datatable.PositionChanged += new EventHandler(dhh_datatable_PositionChanged_EmpRice);
                dgvCom_DanhSach.AutoGenerateColumns = false;
                dgvCom_DanhSach.DataSource = dt_datatable;
                NV_Com_Xuat_thong_tin();
            }
            catch (Exception)
            {
            }
        }

        private void dhh_datatable_PositionChanged_EmpRice(object sender, EventArgs e)
        {
            NV_Com_Xuat_thong_tin();
        }

        private void NV_Com_Load_AllEmpRice()
        {
            dt_datatable = UsingSql.GetAllEmpRiceList();
            if (dt_datatable != null)
            {
                dhh_datatable = BindingContext[dt_datatable];
                dhh_datatable.PositionChanged += new EventHandler(dhh_datatable_PositionChanged_EmpRice);
                dgvCom_DanhSach.AutoGenerateColumns = false;
                dgvCom_DanhSach.DataSource = dt_datatable;
                NV_Com_Xuat_thong_tin();
            }
        }

        private void NV_Com_Xuat_thong_tin()
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_datatable.Current;
                if (rbtnCom_NhanVien.Checked)
                {
                    lbox_Com_NhanVien_BoPhan.SelectedValue = drv["EmployeeID"].ToString();
                }
                if (rbtnCom_BoPhan.Checked)
                {
                    lbox_Com_NhanVien_BoPhan.SelectedValue = drv["DepartmentID"].ToString();
                }
                dtiCom_Ngay.Text = drv["EmpRiceDate"].ToString();
                txtCom_GhiChu.Text = drv["Note"].ToString();
            }
            catch (Exception)
            {
            }
        }

        private List<EmpRice> NV_Com_Get_EmpRiceList_Selected()
        {
            List<EmpRice> list = new List<EmpRice>();
            if (rbtnCom_NhanVien.Checked)
            {
                foreach (DataRowView item in lbox_Com_NhanVien_BoPhan.SelectedItems)
                {
                    EmpRice erice = new EmpRice()
                    {
                        EmpID = item[0].ToString(),
                        EmpRiceDate = new DateTime(dtiCom_Ngay.Value.Year
                                                    , dtiCom_Ngay.Value.Month
                                                    , dtiCom_Ngay.Value.Day),
                        Note = txtCom_GhiChu.Text
                    };
                    list.Add(erice);
                }
            }
            if (rbtnCom_BoPhan.Checked)
            {
                foreach (DataRowView item in lbox_Com_NhanVien_BoPhan.SelectedItems)
                {
                    DataTable table = UsingSql.GetEmpListByDeptID(item[0].ToString());
                    foreach (DataRowView row in table.DefaultView)
                    {
                        EmpRice erice = new EmpRice()
                        {
                            EmpID = row[0].ToString(),
                            EmpRiceDate = new DateTime(dtiCom_Ngay.Value.Year
                                                    , dtiCom_Ngay.Value.Month
                                                    , dtiCom_Ngay.Value.Day),
                            Note = txtCom_GhiChu.Text
                        };
                        list.Add(erice);
                    }
                }
            }
            return list;
        }

        private void Event_1()
        {
            btnCom_GhiNhan.Text = "Ghi Nhận";
            btnCom_Xoa.Text = "Hủy";
            NV_Com_EnableTrueAll();
            dgvCom_DanhSach.Enabled = false;
            lbox_Com_NhanVien_BoPhan.SelectionMode = SelectionMode.MultiExtended;
        }

        private void Event_2()
        {
            btnCom_GhiNhan.Text = "Tạo Mới";
            btnCom_Xoa.Text = "Xóa";
            NV_Com_EnableFalseAll();
            dgvCom_DanhSach.Enabled = true;
            NV_Com_Xuat_thong_tin();
            lbox_Com_NhanVien_BoPhan.SelectionMode = SelectionMode.One;
        }

        private void rbtnCom_NhanVien_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnCom_NhanVien.Checked == true)
            {
                lblNV_Com_Ten.Text = "Tên nhân viên";
                DataTable table = UsingSql.GetEmployeeList();
                lbox_Com_NhanVien_BoPhan.DataSource = table;
                lbox_Com_NhanVien_BoPhan.DisplayMember = "FullName";
                lbox_Com_NhanVien_BoPhan.ValueMember = "EmployeeID";
            }
        }

        private void rbtnCom_BoPhan_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnCom_BoPhan.Checked == true)
            {
                lblNV_Com_Ten.Text = "Tên bộ phận";
                DataTable table = UsingSql.Rice_getDepartmentList();
                lbox_Com_NhanVien_BoPhan.DataSource = table;
                lbox_Com_NhanVien_BoPhan.DisplayMember = "DepartmentName";
                lbox_Com_NhanVien_BoPhan.ValueMember = "DepartmentID";
            }
        }

        private void btnCom_GhiNhan_Click(object sender, EventArgs e)
        {
            if (btnCom_GhiNhan.Text == "Tạo Mới")
            {
                Event_1();
            }
            else
            {
                try
                {
                    List<EmpRice> list = NV_Com_Get_EmpRiceList_Selected();
                    UsingSql.insert_EmpRice(list);
                    NV_Com_Load_AllEmpRice();
                    Event_2();
                    //btnCom_Xem_Click(sender, e);
                }
                catch (Exception)
                { 
                }
            }
        }

        private void btnCom_Xoa_Click(object sender, EventArgs e)
        {
            if (btnCom_Xoa.Text == "Hủy")
            {
                Event_2();
            }
            else
            {
                try
                {
                    List<EmpRice> list = NV_Com_Get_EmpRiceList_Selected();
                    if (UsingSql.delete_EmpRice(list) == 1)
                    {
                        dhh_datatable.RemoveAt(dhh_datatable.Position);
                        dhh_datatable.EndCurrentEdit();
                        NV_Com_Xuat_thong_tin();
                        Event_2();
                    }
                }
                catch (Exception)
                {

                }
            }
        }

        private void txtCom_Tim_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string tim = txtCom_Tim.Text.Trim();
                string chuoi_tim = "FullName like '*" + tim + "*'";
                dt_datatable.DefaultView.RowFilter = chuoi_tim;
                //NV_Com_Xuat_thong_tin();
            }
            catch (Exception)
            {
                //dt_datatable.DefaultView.RowFilter = "EmployeeID is not null";                
            }
        }

        private void txtCom_Tim_Click(object sender, EventArgs e)
        {
            txtCom_Tim.SelectAll();
        }


        #endregion

        #region QUAN LY SU KIEN

        private void SK_HideAll()
        {
            groupSK_ThoiGian.Visible = false;
            txtSK_Tim.Visible = false;
            groupSK_ThongTin.Visible = false;
            dgvSK_DanhSach.Visible = false;
        }

        private void SK_ShowAll()
        {
            groupSK_ThoiGian.Location = new Point(10, 106);
            groupSK_ThoiGian.Size = new Size(437, 121);
            groupSK_ThoiGian.Visible = true;
            groupSK_ThongTin.Location = new Point(10, 261);
            groupSK_ThongTin.Size = new Size(437, 363);
            groupSK_ThongTin.Visible = true;
            dgvSK_DanhSach.Location = new Point(453, 118);
            dgvSK_DanhSach.Size = new Size(563, 353);
            dgvSK_DanhSach.Visible = true;
            dtiSK_TuNgay.Value = DateTime.Now;
            dtiSK_DenNgay.Value = DateTime.Now;
            dtiSK_Ngay.Value = DateTime.Now;
            txtSK_Tim.Location = new Point(10, 229);
            txtSK_Tim.Size = new Size(437, 26);
            txtSK_Tim.Visible = true;
        }

        private void SK_EnableFalseAll()
        {            
            dgvSK_DanhSach.Enabled = false;
            //txtSK_Tim.Enabled = false;
            cbbSK_BoPhan.Enabled = false;
            cbbSK_LoaiSuKien.Enabled = false;
            lboxSK_NhanVien.Enabled = false;
            txtSK_GhiChu.Enabled = false;
            btnSK_GhiNhan.Enabled = false;
        }

        private void SK_EnableTrueAll()
        {            
            dgvSK_DanhSach.Enabled = true;
            cbbSK_BoPhan.Enabled = true;
            cbbSK_LoaiSuKien.Enabled = true;
            lboxSK_NhanVien.Enabled = true;
            txtSK_GhiChu.Enabled = true;
            btnSK_GhiNhan.Enabled = true;
        }

        private void btnSK_Xem_Click(object sender, EventArgs e)
        {
            DateTime dateBegin = dtiSK_TuNgay.Value;
            DateTime dateEnd = dtiSK_DenNgay.Value;
            dateBegin = new DateTime(dateBegin.Year, dateBegin.Month, dateBegin.Day);
            dateEnd = new DateTime(dateEnd.Year, dateEnd.Month, dateEnd.Day);
            dateEnd = dateEnd.AddDays(1);
            dateEnd = dateEnd.AddSeconds(-1);
            dt_datatable = UsingSql.getEventLog(dateBegin, dateEnd);
            if (dt_datatable == null || dt_datatable.Rows.Count == 0)
            {
                MessageBox.Show("Không tìm thấy dữ liệu");
                dgvSK_DanhSach.DataSource = null;
            }
            else
            {
                dhh_datatable = BindingContext[dt_datatable];
                dhh_datatable.PositionChanged += new EventHandler(dhh_datatable_PositionChanged_LogEvent);
                dgvSK_DanhSach.AutoGenerateColumns = false;
                dgvSK_DanhSach.DataSource = dt_datatable;
                txtSK_Tim.Enabled = true;
                SK_Xuat_thong_tin();
            }
        }

        private void dhh_datatable_PositionChanged_LogEvent(object sender, EventArgs e)
        {
            SK_Xuat_thong_tin();
        }

        private void SK_Xuat_thong_tin()
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_datatable.Current;
                lboxSK_NhanVien.SelectedValue = drv["EmployeeID"].ToString();
                cbbSK_LoaiSuKien.SelectedValue = drv["EventID"].ToString();
                dtiSK_Ngay.Text = drv["EventDate"].ToString();
                txtSK_GhiChu.Text = drv["Note"].ToString();
            }
            catch (Exception)
            {

            }
        }

        private void btnSK_DieuChinh_Click(object sender, EventArgs e)
        {
            SK_HideAll();
            SK_ShowAll();
            SK_EnableFalseAll();
            btnSK_Xoa.Text = "Xóa";
            lboxSK_NhanVien.SelectionMode = SelectionMode.One;
            dgvSK_DanhSach.Enabled = true;
            txtSK_Tim.Text = Noi_dung;
            SK_Load_DepartmentList();
            SK_Load_EventTypeList();
            SK_Load_AllEventLog();
        }

        private void SK_Load_DepartmentList()
        {
            DataTable table = UsingSql.Rice_getDepartmentList();
            DataRow row = table.NewRow();
            row[0] = 0;
            row[1] = "Tất cả";
            table.Rows.Add(row);
            cbbSK_BoPhan.DataSource = table;
            cbbSK_BoPhan.ValueMember = "DepartmentID";
            cbbSK_BoPhan.DisplayMember = "DepartmentName";
            cbbSK_BoPhan.SelectedValue = 0;
        }

        private void SK_Load_EventTypeList()
        {
            DataTable table = UsingSql.getEventType();
            if (table != null && table.Rows.Count > 0)
            {
                cbbSK_LoaiSuKien.DataSource = table;
                cbbSK_LoaiSuKien.ValueMember = "EventID";
                cbbSK_LoaiSuKien.DisplayMember = "EventName";
            }
        }

        private void SK_Load_AllEventLog()
        {
            dt_datatable = UsingSql.getAllEventLog();
            dhh_datatable = BindingContext[dt_datatable];
            dhh_datatable.PositionChanged += new EventHandler(dhh_datatable_PositionChanged_LogEvent);
            dgvSK_DanhSach.AutoGenerateColumns = false;
            dgvSK_DanhSach.DataSource = dt_datatable;
        }

        private void cbbSK_BoPhan_SelectedValueChanged(object sender, EventArgs e)
        {
            DataTable table = null;
            if (cbbSK_BoPhan.SelectedValue.ToString() != "0")
            {
                table = UsingSql.GetEmpListByDeptID(cbbSK_BoPhan.SelectedValue.ToString());
            }
            else
            {
                table = UsingSql.GetEmployeeList();
            }
            lboxSK_NhanVien.DataSource = table;
            lboxSK_NhanVien.ValueMember = "EmployeeID";
            lboxSK_NhanVien.DisplayMember = "FullName";
        }

        private void btnSK_GhiNhan_Click(object sender, EventArgs e)
        {
            List<LogEvent> list = new List<LogEvent>();
            foreach (DataRowView item in lboxSK_NhanVien.SelectedItems)
            {
                LogEvent log = new LogEvent
                {
                    EmployeeID = item[0].ToString(),
                    EventDate = new DateTime(dtiSK_Ngay.Value.Year
                                            , dtiSK_Ngay.Value.Month
                                            , dtiSK_Ngay.Value.Day),
                    Note = txtSK_GhiChu.Text,
                    EventID = Convert.ToInt32(cbbSK_LoaiSuKien.SelectedValue.ToString())
                };
                list.Add(log);
            }
            if (UsingSql.insert_EventLog(list) != -1)
                MessageBox.Show("Thêm dữ liệu thành công");
            else
                MessageBox.Show("Dữ liệu đã tồn tại");
            SK_Load_AllEventLog();
        }

        private void riQL_KyLuat_Click(object sender, EventArgs e)
        {
            SK_HideAll();
        }

        private void btnSK_Xoa_Click(object sender, EventArgs e)
        {
            if (btnSK_Xoa.Text == "Xóa")
            {
                DialogResult result = MessageBox.Show("Bạn có chắc muốn xóa???", "Xác nhận", MessageBoxButtons.YesNo
                                                        , MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
                if (result == DialogResult.Yes)
                {
                    LogEvent log = new LogEvent
                    {
                        EmployeeID = lboxSK_NhanVien.SelectedValue.ToString(),
                        EventDate = new DateTime(dtiSK_Ngay.Value.Year, dtiSK_Ngay.Value.Month, dtiSK_Ngay.Value.Day),
                        EventID = Convert.ToInt32(cbbSK_LoaiSuKien.SelectedValue.ToString())
                    };
                    if (UsingSql.delete_EventLog(log) == 1)
                    {
                        dhh_datatable.RemoveAt(dhh_datatable.Position);
                        dhh_datatable.EndCurrentEdit();
                        SK_Xuat_thong_tin();
                    }
                }
            }
            else
            {
                btnSK_DieuChinh_Click(sender, e);
            }
        }

        private void btnSK_TaoMoi_Click(object sender, EventArgs e)
        {
            SK_HideAll();
            SK_ShowAll();
            this.groupSK_ThongTin.Location = this.groupSK_ThoiGian.Location;
            txtSK_Tim.Visible = false;
            SK_EnableTrueAll();
            btnSK_Xoa.Text = "Hủy";
            dgvSK_DanhSach.Enabled = false;
            lboxSK_NhanVien.SelectionMode = SelectionMode.MultiExtended;
            SK_Load_DepartmentList();
            SK_Load_EventTypeList();
            SK_Load_AllEventLog();
        }

        private void txtSK_Tim_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string tim = txtSK_Tim.Text.Trim();
                string chuoi_tim = "FullName like '*" + tim + "*'";
                dt_datatable.DefaultView.RowFilter = chuoi_tim;
            }
            catch (Exception) { }
        }

        private void txtSK_Tim_Click(object sender, EventArgs e)
        {
            txtSK_Tim.SelectAll();
        }


        #endregion

        

        

        
        

        
        

        
    }
}
